Went with union-find pretty quickly, which felt right.
Use Union-Find (Disjoint Set Union) to dynamically maintain connected components as cells are added. For each new land cell, increment the island count, then union it with any adjacent land cells, decrementing the count for each successful union. This yields O(1) amortized time per operation with path compression and union by rank.
Pro tip: Mention that Union-Find is optimal here because it handles incremental connectivity efficiently, and briefly compare with BFS/DFS which would be O(m*n) per operation. Also, discuss the trade-off between path compression and union by rank for near-constant time.
Confirm that the grid starts as all water, and each operation flips a water cell to land. Ask about grid size, number of operations, and whether positions are guaranteed unique and within bounds.
Select Union-Find (Disjoint Set Union) to efficiently track connected components of land cells. Explain why it's better than re-running BFS/DFS after each operation.
Initialize a DSU for all cells. For each operation, mark the cell as land, increment island count, then check its four neighbors; if a neighbor is land, union the two cells and decrement the count if they were in different sets.
State that with path compression and union by rank, each operation is nearly O(1) amortized, total O(k α(mn)) for k operations. Discuss edge cases like duplicate positions, boundary cells, and no land.
Write clean code for DSU with find and union methods, then test with small examples and edge cases to ensure correctness.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.