DSA Tracker

Medium

Number of Islands

A medium Graph problem included in Apna College, Love Babbar 450, Striver A2Z. Below: the roles whose interviews prioritise this topic, and how to practise it.

Topic
Graph
Sheets
3
Core for
11 roles
Platform
LeetCode

The problem

Given a 2D grid map of '1's (land) and '0's (water), count the number of islands. An island is formed by connecting adjacent lands horizontally or vertically, and is surrounded by water on all sides.

Example 1

Input
grid = [["1","1","1","1","0"],["1","1","0","1","0"],["1","1","0","0","0"],["0","0","0","0","0"]]
Output
1
Why
All the 1s are connected, forming a single island.

Example 2

Input
grid = [["1","1","0","0","0"],["1","1","0","0","0"],["0","0","1","0","0"],["0","0","0","1","1"]]
Output
3
Why
There are three separate groups of connected 1s.

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 300
  • grid[i][j] is '0' or '1'

How to think about it

Updated 2026-09-09

Every unvisited land cell is an undiscovered piece of territory. When a sweep finds one, you have discovered an entirely new island, so increment the counter and immediately flood the entire component into visited state before resuming the scan. The grid itself can serve as its own visited log by sinking land to water.

Approaches, worst first

  1. Connected component with global visited set

    time O(m * n) · space O(m * n)

    Scan row by row. Whenever a '1' is not in a hash set of visited coordinates, fire a BFS or DFS traversal adding every reachable neighbor into the set. Correct, but allocating coordinates into a hash set adds heavy hashing overhead and pointer indirection.

  2. In-place grid sinking DFS or BFSWrite this one

    time O(m * n) · space O(m * n)

    When encountering '1', trigger an in-place flood fill that mutates visited cells from '1' to '0'. This eliminates external tracking structures entirely, leaving only the recursion stack or queue bounded by grid size.

Where people lose marks · 3
  • In deep or snake-shaped islands on a 300x300 grid, recursive DFS can reach recursion depths up to 90,000, which will exceed call stack limits in languages with standard stack sizes.
  • Forgetting to mark a cell visited as soon as it is enqueued in BFS rather than when dequeued, causing identical adjacent cells to be added to the queue exponentially many times and producing memory exhaustion.
  • Comparing grid values as numbers instead of characters; `grid[i][j] === 1` silently fails when inputs are strings '1'.

Full solution

In-place grid sinking BFS: flood each newly found island to water as it is counted, so no external visited set is needed and, unlike recursive DFS, the queue never risks blowing the call stack on a large grid.

Python
from collections import deque


def num_islands(grid: list[list[str]]) -> int:
    rows, cols = len(grid), len(grid[0])
    count = 0
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] != "1":
                continue
            count += 1
            # BFS sinks the whole component to "0" so it is never counted again,
            # and a queue avoids the recursion-depth blowup a DFS risks on a big grid.
            queue = deque([(r, c)])
            grid[r][c] = "0"
            while queue:
                cr, cc = queue.popleft()
                for nr, nc in ((cr - 1, cc), (cr + 1, cc), (cr, cc - 1), (cr, cc + 1)):
                    if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == "1":
                        grid[nr][nc] = "0"
                        queue.append((nr, nc))
    return count
JavaScript
function numIslands(grid) {
  const rows = grid.length;
  const cols = grid[0].length;
  let count = 0;
  for (let r = 0; r < rows; r++) {
    for (let c = 0; c < cols; c++) {
      if (grid[r][c] !== "1") continue;
      count++;
      const queue = [[r, c]];
      grid[r][c] = "0";
      while (queue.length) {
        const [cr, cc] = queue.shift();
        for (const [nr, nc] of [[cr - 1, cc], [cr + 1, cc], [cr, cc - 1], [cr, cc + 1]]) {
          if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && grid[nr][nc] === "1") {
            grid[nr][nc] = "0";
            queue.push([nr, nc]);
          }
        }
      }
    }
  }
  return count;
}
Try it in the editor

The theory behind it

Graph — the ground this problem stands on. All Graph problems

What Graph is

A graph is a network of individual points, called vertices or nodes, connected by lines called edges. Think of a subway transit map, an electrical circuit, or a web of social friends. Unlike a tree, a graph has no designated top node and no parent-child hierarchy. Connections can run one-way or both ways, and paths can loop back on themselves to form closed cycles.

When to reach for it

Reach for graph algorithms when inputs describe relationships, networks, flights between cities, course prerequisites, or clone networks. Signals include finding the shortest route across unweighted connections, ordering tasks that depend on earlier tasks, counting isolated clusters, or checking whether a path contains an infinite loop. Whenever problems present pairs of related entities and ask for reachability, distances, or dependencies, graph representations apply.

How the pattern works

First convert edge lists into an adjacency list, mapping each node to an array of its neighbors. Choose your exploration strategy based on the goal: use a queue and breadth-first search to find the shortest path in unweighted networks, or use recursion and depth-first search to explore full paths and detect cycles. Because graphs can have loops, always track visited nodes in a set or boolean array. Add nodes to the visited set at the moment they enter the queue so they are never visited twice.

What each operation costs

OperationTime
visit all nodes and edges via searchO(v + e)
topological sort using in-degree countsO(v + e)
shortest path using dijkstra with a min-heapO((v + e) log v)
What usually goes wrong with Graph
  • Adding a node to the visited set when popping from the queue instead of when pushing, which lets neighboring nodes enqueue duplicate entries and wastes memory.
  • Failing to check for cycles in directed graphs when finding prerequisite orders, causing topological sort routines to hang or return incomplete lists.
  • Assuming an input graph is fully connected and scanning from only a single starting node, missing disconnected islands and isolated components.

Which roles need this problem

Graph is a core topic for these 11 roles — if you're targeting one of them, this problem is early in your path, not optional.

Secondary for 6 more roles, including Performance Engineer, Search Engineer, Information Retrieval Engineer.

Track this in your role's order

Pick your target role and all 370 problems — including this one — resequence to what that interview actually asks. Free.

Start free

More Graph problems

Problem set and role mapping as of .