Detecting Cycles in Graphs with Union-Find

🚀 Day 24/100 — Problem: Detects if a graph has a cycle Using Disjoint Set (Union-Find) Concept: Union-Find - Each node belongs to a set - Union → connect two nodes - Find → check root parent class UnionFind: def __init__(self, n): self.parent = list(range(n)) def find(self, x): if self.parent[x] != x: self.parent[x] = self.find(self.parent[x]) # path compression return self.parent[x] def union(self, x, y): px, py = self.find(x), self.find(y) if px == py: return True # cycle detected self.parent[py] = px return False What I learned: Efficient grouping helps solve connectivity problems Path compression makes it fast. Time Complexity: ~O(α(n)) #100DaysOfCode #DSA #UnionFind #Graphs #CodingInterview #ProblemSolving #PlacementPrep #LearnInPublic

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories