10. Number of Islands
mediumAsked at RedisCount connected '1' regions in a 2D grid; Redis uses it to verify clean BFS/DFS hygiene before discussing cluster-partition reconnection.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an m x n 2D grid of '1' (land) and '0' (water), return the number of islands. An island is surrounded by water and formed by connecting adjacent land cells horizontally or vertically.
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"],["0","1","0"],["1","1","1"]]1Approaches
1. Union-Find every land cell
Union each land cell with its right/down neighbor; count distinct roots.
- Time
- O(m*n * α)
- Space
- O(m*n)
// Build DSU sized m*n, union land-land neighbors, count roots.Tradeoff:
2. DFS flood-fill
Scan the grid; on each unvisited '1' DFS-sink the whole island and increment a counter.
- Time
- O(m*n)
- Space
- O(m*n) worst case for recursion stack
function numIslands(grid) {
let count = 0;
const m = grid.length, n = grid[0].length;
function 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:
Redis-specific tips
Redis interviewers like a quick analogy to gossip protocols in Redis Cluster — mention how flood-fill mirrors how reachability info spreads across shard nodes.
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 Redis interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →