πDay 4. Undirected Graph Cycle π§
The problem can be found at the following link: Question Link
π‘ Problem Description:
Given an undirected graph with V
vertices and E
edges, represented as a 2D vector edges[][]
, where each entry edges[i] = [u, v]
denotes an edge between vertices u
and v
, determine whether the graph contains a cycle or not.
Note: Sorry for uploading late, my exam is going on.
π Example Walkthrough:
Example 1:
Input:
V = 4, E = 4
edges = [[0, 1], [0, 2], [1, 2], [2, 3]]
Output:
True
Explanation:
There exists a cycle: 1 β 2 β 0 β 1
Example 2:
Input:
V = 4, E = 3
edges = [[0, 1], [1, 2], [2, 3]]
Output:
False
Explanation:
No cycle exists in the given graph.
Constraints:
$1 \leq V \leq 10^5$
$1 \leq E = \text{edges.size()} \leq 10^5$
π― My Approach:
Optimized Approach: Union-Find with Path Compression
Algorithm Steps:
Initialize a parent array where each node is its own parent (
-1
).Find function with path compression to efficiently determine the representative parent of each node.
Union function with union by size to merge sets efficiently.
Iterate over all edges and apply union-find:
If both nodes of an edge belong to the same set, a cycle is detected.
Otherwise, perform a union operation to merge them.
Return true if a cycle is found, otherwise return false.
π Time and Auxiliary Space Complexity
Expected Time Complexity:
O(E * Ξ±(V))
, whereΞ±(V)
is the inverse Ackermann function, which grows extremely slowly and is nearly constant.Expected Auxiliary Space Complexity:
O(V)
, as we store only the parent array.
π Solution Code
Code (C++)
class Solution {
public:
bool isCycle(int V, vector<vector<int>>& edges) {
vector<int> p(V, -1);
function<int(int)> f = [&](int x){ return p[x] < 0 ? x : p[x] = f(p[x]); };
for(auto &e : edges){
int a = f(e[0]), b = f(e[1]);
if(a == b) return true;
if(p[a] > p[b]) swap(a, b);
p[a] += p[b]; p[b] = a;
}
return false;
}
};
Code (Java)
class Solution {
public boolean isCycle(int V, int[][] edges) {
int[] p = new int[V];
Arrays.fill(p, -1);
for (int[] e : edges) {
int a = f(p, e[0]), b = f(p, e[1]);
if (a == b) return true;
if (p[a] > p[b]) { int t = a; a = b; b = t; }
p[a] += p[b]; p[b] = a;
}
return false;
}
int f(int[] p, int x) {
return p[x] < 0 ? x : (p[x] = f(p, p[x]));
}
}
Code (Python)
class Solution:
def isCycle(self, V, edges):
p = [-1]*V
def f(x): return x if p[x]<0 else f(p[x])
for u,v in edges:
a, b = f(u), f(v)
if a == b: return True
if p[a] > p[b]: a,b = b,a
p[a] += p[b]; p[b] = a
return False
π― Contribution and Support:
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Letβs make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated