Implement Union-Find for connectivity
Problem Description
Design and implement a Disjoint Set Union (DSU) data structure, also known as Union-Find. Your implementation must incorporate two key optimizations: path compression and union by rank.
The DSU structure should support the following operations:
make_set(x): Creates a new set containing only elementx.find(x): Returns the representative (root) of the set containingx.union(x, y): Merges the sets containingxandy.connected(x, y): Returnstrueifxandyare in the same set,falseotherwise.
Application
After implementing the DSU, apply it to solve the following problem:
Given an undirected graph with n nodes, labeled from 1 to n, and an initial list of edges, process q online connectivity queries efficiently. Each query will ask whether two given nodes are connected.
Requirements
- Provide a complete implementation of the DSU data structure.
- Analyze the time and space complexity of your solution, both for the DSU operations and the overall graph connectivity problem.
- Discuss how your implementation handles edge cases, specifically duplicate union operations and isolated nodes.
AI interview prep
Core dilemma
Efficiently maintaining and querying dynamic connectivity in a graph with optimal performance for a large number of online operations, balancing the cost of updates (unions) and queries (find/connected).
3 tradeoffs and 3 stress tests locked
Interview prep
Unlock the interviewer X-Ray rubric, tradeoff matrix, stress tests, clarifying questions, and key concepts.
Implement Union-Find for connectivity
Problem Description
Design and implement a Disjoint Set Union (DSU) data structure, also known as Union-Find. Your implementation must incorporate two key optimizations: path compression and union by rank.
The DSU structure should support the following operations:
make_set(x): Creates a new set containing only elementx.find(x): Returns the representative (root) of the set containingx.union(x, y): Merges the sets containingxandy.connected(x, y): Returnstrueifxandyare in the same set,falseotherwise.
Application
After implementing the DSU, apply it to solve the following problem:
Given an undirected graph with n nodes, labeled from 1 to n, and an initial list of edges, process q online connectivity queries efficiently. Each query will ask whether two given nodes are connected.
Requirements
- Provide a complete implementation of the DSU data structure.
- Analyze the time and space complexity of your solution, both for the DSU operations and the overall graph connectivity problem.
- Discuss how your implementation handles edge cases, specifically duplicate union operations and isolated nodes.