Problem
Given an undirected, connected graph, find the minimum cut (the smallest set of edges whose removal disconnects the graph) using Karger’s randomized algorithm.
Example
Example 1
|
|
Solution
Method 1 – Karger’s Randomized Contraction Algorithm
Intuition
Karger’s algorithm repeatedly contracts random edges in the graph until only two vertices remain. The number of edges between these two vertices is a candidate for the minimum cut. By running the algorithm multiple times, we can find the true minimum cut with high probability.
Approach
- While there are more than 2 vertices:
- Pick a random edge (u, v).
- Merge (contract) u and v into a single vertex, combining their edges.
- Remove self-loops.
- When only two vertices remain, the number of edges between them is a cut.
- Repeat the process multiple times and return the smallest cut found.
Code
|
|
Complexity
- ⏰ Time complexity:
O(n^4)
, as the contraction is repeated O(n^2) times and each contraction is O(n^2). - 🧺 Space complexity:
O(n^2)
, for storing edges and parent arrays.