Question presented to candidate: "You have solved number of islands with DFS. Now compare DFS, BFS and Union-Find for this problem — their costs, their risks, and when you would choose each — and implement the Union-Find version in Python."
What a strong answer should cover:
- All three are O(rows × cols) for a single count (Union-Find with path compression and union by size is O(α(n)) per operation, effectively constant).
- Memory shape: DFS stack (or recursion) vs BFS queue vs Union-Find's full
parent/sizearrays; recursive DFS can hit the recursion limit. - Union-Find counts as land − successful unions, looking only right and down from each cell.
- Union-Find shines when land arrives incrementally (Number of Islands II); it cannot handle removals; BFS is the one that gives distances.
- Python details: iterative
find(no recursion),list(range(n))forparent,collections.dequefor BFS, and the 1000-frame recursion limit for recursive DFS.
Code / implementation expected: Yes — a Union-Find (with path halving and union by size) over cell ids r * cols + c, in Python.