VOOZH about

URL: https://www.geeksforgeeks.org/dsa/karps-minimum-mean-average-weight-cycle-algorithm/

⇱ Karp's minimum mean (or average) weight cycle algorithm - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Karp's minimum mean (or average) weight cycle algorithm

Last Updated : 23 Jul, 2025

Given a directed and strongly connected graph with non-negative edge weights. We define the mean weight of a cycle as the summation of all the edge weights of the cycle divided by the no. of edges. Our task is to find the minimum mean weight among all the directed cycles of the graph.

The input is provided as a list of edges, where each edge is represented by a triplet [u, v, w] indicating a directed edge from node u to node v with weight w. Nodes are labeled from 0 to n-1, and the graph is guaranteed to be strongly connected, meaning a path exists between every pair of nodes.

Example:

Input: [[0, 1, 1], [0, 2, 10], [1, 2, 3], [2, 3, 2], [3, 1, 0], [3, 0, 8]]

👁 112

Output: 1.66667

Approach:

Method to find the smallest mean weight value cycle efficiently  

Step 1: Choose first vertex as source.

Step 2: Compute the shortest path to all other vertices
on a path consisting of k edges 0 <= k <= V
where V is number of vertices.
This is a simple dp problem which can be computed
by the recursive solution
dp[k][v] = min(dp[k][v], dp[k-1][u] + weight(u,v)
where v is the destination and the edge(u,v) should
belong to E

Step 3: For each vertex calculate max(dp[n][v]-dp[k][v])/(n-k)
where 0<=k<=n-1

Step 4: The minimum of the values calculated above is the
required answer.

Implementation:


Output
1.66667

Time Complexity : The time complexity of the given program is O(V^3), where V is the number of vertices in the graph. This is because the program uses a nested loop to fill up the dp table, and the size of the dp table is V^2. The outermost loop runs V times, the middle loop runs V times, and the innermost loop can run up to V times in the worst case, giving a total time complexity of O(V^3). The other parts of the program have a lower time complexity and do not contribute significantly to the overall time complexity.

Space Complexity : The space complexity of the given  program is O(V^2), where V is the number of vertices in the graph. This is because the program creates a 2D array dp of size (V+1)xV, which requires O(V^2) space. Additionally, the program creates a vector of edges, which takes up O(E) space, where E is the number of edges in the graph. However, in this particular implementation, the number of edges is not directly stored, and it is not clear whether all edges are actually added to the vector. Therefore, the space complexity is mainly determined by the size of the dp array, which is O(V^2).

Comment
Article Tags: