Skip to the solution
MediumDSA9 min read

What is the Union-Find (Disjoint Set) data structure?

119 views

The problem

Question presented to candidate: "Can you explain what a Union-Find, or disjoint set, data structure is, implement it in Python, and tell me how fast its operations are and why?"

What a strong answer should cover:

  • What it stores: a partition of elements into non-overlapping sets, each set represented by one root; the whole thing is a forest kept in a parent array.
  • The two operations: find(x) walks parent pointers to the root; union(a, b) links one root under the other and reports whether a merge happened.
  • The two optimisations and what each fixes: path compression flattens paths during find; union by size or rank keeps trees shallow (height at most log2 n). Together: amortised O(ฮฑ(n)) per operation, effectively constant.
  • Where it is used: connected components, cycle detection in an undirected graph, Kruskal's minimum spanning tree, grouping problems; and what it cannot do (split a set, or answer questions on directed graphs).
  • Python specifics: store parent and size as plain lists for integer elements (or a dict with setdefault for arbitrary hashable keys), and write find iteratively, because a recursive find on a long chain hits the default recursion limit of 1000 and raises RecursionError.

Code / implementation expected: Yes โ€” a DSU class in Python with find, union returning a bool, and a set count.

  • union-find

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

9 min read ยท 11 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonUnion-Find with path compression and union by size
PythonCounting parent hops: naive vs compression vs union by size
PythonThree classic problems: components, redundant edge, earliest connection

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 124 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you find the longest palindromic substring?

Continue