21. Number of Islands
mediumAsked at SquarespaceCount connected groups of land cells in a 2D grid; Squarespace uses it to test grid traversal via BFS or DFS without redundant work.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given a 2D grid of '1's (land) and '0's (water), return the number of islands. An island is a 4-directionally connected group of land cells; the grid's edges count as water.
Constraints
1 <= m, n <= 300grid[i][j] is '0' or '1'
Examples
Example 1
grid=[["1","1","0"],["1","0","0"],["0","0","1"]]2Example 2
grid=[["1","1","1","1","0"],["1","1","0","1","0"],["0","0","0","0","0"]]1Approaches
1. Union-find on every pair
Build a DSU and union neighboring land cells, then count roots.
- Time
- O(mn * alpha)
- Space
- O(mn)
// build DSU, union each land cell with its right/down neighbor if also land,
// then count distinct roots over land cells.Tradeoff:
2. DFS flood fill in place
Scan the grid; on each unvisited '1' increment the count and DFS to sink the whole island. Mutates the grid to track visits.
- Time
- O(mn)
- Space
- O(mn)
function numIslands(grid) {
const m = grid.length, n = grid[0].length;
let count = 0;
const sink = (i, j) => {
if (i < 0 || j < 0 || i >= m || j >= n || grid[i][j] !== '1') return;
grid[i][j] = '0';
sink(i + 1, j); sink(i - 1, j); sink(i, j + 1); sink(i, j - 1);
};
for (let i = 0; i < m; i++)
for (let j = 0; j < n; j++)
if (grid[i][j] === '1') { count++; sink(i, j); }
return count;
}Tradeoff:
Squarespace-specific tips
Squarespace likes when you mention this flood-fill matches their template-layout adjacency check that finds connected block groups for drag-and-drop section moves.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Number of Islands and other Squarespace interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →