The Number of Islands II problem presents an initially all-water grid. A sequence of land-addition operations is given: each operation converts a water cell to land. After each operation, report the current number of islands. This hard coding problem requires dynamic connectivity updates — exactly what Union-Find is designed for.
Uber, Meta, Dropbox, Amazon, TikTok, and Google ask this because it's the canonical Union-Find dynamic connectivity problem. Unlike static island counting (DFS/BFS), additions require efficiently merging components. The array, union find, and hash table interview pattern is the core, and the problem demonstrates why Union-Find is superior to DFS for dynamic problems.
Union-Find with online updates. Initialize all cells as water (no components). For each addition at (r,c): set cell as land, increment island count by 1 (new independent island). For each of the 4 neighbors: if the neighbor is land and in a different component, union them and decrement the island count by 1. Use path compression and union-by-rank for efficiency.
Grid 3×3. Operations: [(0,0),(0,1),(1,2),(2,1),(1,1)].
r * cols + c.Number of Islands II is the prototypical Union-Find problem for dynamic graph problems. The pattern: initialize, add node, check neighbors, union if in different components, track component count. This pattern generalizes to "count connected components after adding edges," "friend circle problem with dynamic additions," and "network connectivity monitoring." Master the 2D→1D index mapping and Union-Find with path compression — these are the two technical building blocks needed.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Longest Consecutive Sequence | Medium | Solve | |
| First Missing Positive | Hard | Solve | |
| Grid Illumination | Hard | Solve | |
| Maximum Equal Frequency | Hard | Solve | |
| 4Sum II | Medium | Solve |