21. Number of Islands
mediumAsked at ByteDanceCount connected land regions in a grid — ByteDance uses it to test BFS/DFS scaffolding before scaling to user-cluster detection for recommendations.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an m x n grid of '1' (land) and '0' (water), return the number of islands. An island is formed by orthogonally connecting land cells; assume the grid is bordered by water.
Constraints
1 <= m, n <= 300grid[i][j] is '0' or '1'
Examples
Example 1
grid = [["1","1","0"],["1","1","0"],["0","0","1"]]2Example 2
grid = [["1","0","1"],["0","0","0"],["1","0","1"]]4Approaches
1. Union-find every land neighbor
Treat each land cell as a node, union with orthogonal land neighbors, count distinct roots.
- Time
- O(m * n * α)
- Space
- O(m * n)
// build DSU over m*n cells, union orthogonal land neighbors, count rootsTradeoff:
2. DFS flood fill
Scan the grid. On each unvisited land cell, increment the count and flood-fill its connected region in place.
- Time
- O(m * n)
- Space
- O(m * n)
function numIslands(grid) {
const m = grid.length, n = grid[0].length;
let count = 0;
const dfs = (r, c) => {
if (r < 0 || c < 0 || r >= m || c >= n || grid[r][c] !== '1') return;
grid[r][c] = '0';
dfs(r + 1, c); dfs(r - 1, c); dfs(r, c + 1); dfs(r, c - 1);
};
for (let r = 0; r < m; r++) {
for (let c = 0; c < n; c++) {
if (grid[r][c] === '1') { count++; dfs(r, c); }
}
}
return count;
}Tradeoff:
ByteDance-specific tips
ByteDance interviewers want you to flag the recursion-depth risk for 300x300 grids and offer an iterative BFS variant — the same defensive move their backend team makes in production crawlers.
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 ByteDance interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →