মূল কনটেন্টে যান
🌍
গ্লোবাল DSA
প্যাটার্নটপিক 8 · Graphs

8.4 Union Find (Disjoint Set)

চিনবেন কীভাবে
"are X and Y connected", "merge groups", "how many components", edges arriving one at a time — near-O(1) union/find with path compression
Demo · approach · কোড — আগে নিজে চেষ্টা, আটকালে খুলুন

Demo: Redundant ConnectionLC 684 (Medium — Google/Meta High)

Statement (Demo): A tree had one extra edge added, creating a cycle. Given edges, return the edge that can be removed so the graph is a tree again. Example: edges=[[1,2],[1,3],[2,3]][2,3] | ⚡ edges.length ≤ 1000

Approach: For each edge, find the roots of both ends — if they share a root, the ends are already connected, so this edge closes a cycle. Otherwise union them. Path compression in find makes it effectively O(1).

function findRedundantConnection(edges) {
  const parent = Array.from({ length: edges.length + 1 }, (_, i) => i);
  const find = (x) => (parent[x] === x ? x : (parent[x] = find(parent[x]))); // path compression
  for (const [a, b] of edges) {
    const ra = find(a),
      rb = find(b);
    if (ra === rb) return [a, b]; // already connected → cycle
    parent[ra] = rb; // union
  }
}

Complexity: Time O(n α(n)) ≈ O(n), Space O(n)

Demo · Redundant Connectionplan · দিন ০৮০LC 684
নোট · ফাঁকা

প্রবলেম

  • Number of ProvincesLC 547
    (count connected components — also solve with DFS and compare)

    Statement: Given an n × n matrix isConnected where isConnected[i][j] = 1 means cities i and j are directly linked, return the number of provinces (groups of directly or indirectly linked cities).
    Example: isConnected=[[1,1,0],[1,1,0],[0,0,1]]2 | ⚡ n ≤ 200

    নোট · ফাঁকা