I knew Union Find going in but blanked on the exact rank logic mid-implementation.
Start by clarifying the problem and constraints, then explain the Union-Find data structure with path compression and union by rank, including their time complexities. Implement the class with parent and rank arrays, and demonstrate processing the operations with a dry run or code.
Pro tip: Mention that path compression alone gives amortized O(log n) per operation, but combining it with union by rank achieves nearly O(1) amortized time (inverse Ackermann). This shows deep understanding and can impress the interviewer.
Ask about the number of elements, types of operations, and expected time complexity. Confirm if the operations are online or offline, and if there are any memory constraints.
Describe using two arrays: parent to track representatives and rank (or size) to guide union. Explain path compression during find and union by rank during union.
Write the constructor to initialize parent[i] = i and rank[i] = 0. Implement find with recursion or iteration and path compression, and union that attaches smaller rank tree under larger rank tree.
Iterate through the given operations, calling union or find as needed. State that with both optimizations, each operation runs in amortized O(α(n)) time, which is nearly constant.
Walk through a small example to verify correctness, and mention edge cases like union of already connected elements, find on root, and large inputs.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.