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
parentarray. - 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
parentandsizeas plain lists for integer elements (or a dict withsetdefaultfor arbitrary hashable keys), and writefinditeratively, because a recursivefindon a long chain hits the default recursion limit of 1000 and raisesRecursionError.
Code / implementation expected: Yes โ a DSU class in Python with find, union returning a bool, and a set count.