15% off all plans & roadmaps Use code
See plansLeetCode 305 · Solution & editorial
You are given two integers m and n representing the number of rows and columns of a 2D grid, initially filled with water (0). You are also given a list of positions positions, where each positions[i] = [ri, ci] represents adding a land cell (1) at position (ri, ci) in the grid.
Number of Islands II is a Graph Traversal Patterns (DFS & BFS) problem, in the Union-Find (Disjoint Set Union - DSU) subpattern. The pattern covers DFS/BFS traversal, topological sort, shortest paths, Union-Find, and MST
Master Union-Find data structure with path compression and union by rank for connectivity problems.
The reference solution runs in O(k * α(k)) time and O(m * n) space.
Number of Islands II has been reported in interviews at Amazon.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
Number of Islands II is a Graph Traversal Patterns (DFS & BFS) problem, in the Union-Find (Disjoint Set Union - DSU) subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.