Coding problem · Medium · Graphs

Number of Islands

Medium Algorithms & data structures Most askedSeen at Amazon, Google, Meta, Microsoft, Bloomberg

Given an m × n grid of 1 (land) and 0 (water), return the number of islands. An island is a group of land cells connected horizontally or vertically.

Example 1

Input: grid = [[1,1,0,0,0],[1,1,0,0,0],[0,0,1,0,0],[0,0,0,1,1]]
Output: 3

Hints

Hint 1

Scan every cell; when you find unvisited land, count an island and flood-fill (DFS/BFS) to mark all of it visited.

Write and run your solution

Loading the editor… (JavaScript is required to run code in your browser.)

Solution and explanation

Show the solution

Time O(m·n) · Space O(m·n) worst-case recursion/queue

Each time the scan meets unvisited land, increment the count and sink the whole island (set cells to 0) with DFS or BFS so it's not counted again. Every cell is processed a constant number of times.

Reference solution

function numIslands(grid) {
  const m = grid.length, n = grid[0].length;
  const sink = (r, c) => {
    if (r < 0 || c < 0 || r >= m || c >= n || grid[r][c] !== 1) return;
    grid[r][c] = 0;
    sink(r + 1, c); sink(r - 1, c); sink(r, c + 1); sink(r, c - 1);
  };
  let count = 0;
  for (let r = 0; r < m; r++)
    for (let c = 0; c < n; c++)
      if (grid[r][c] === 1) { count++; sink(r, c); }
  return count;
}

Common mistakes

  • Counting diagonal neighbours (only 4 directions).
  • Deep recursion on huge all-land grids — mention BFS or an explicit stack.