L3 · FAANGGraphs~15 min · 6 tests

Number of Islands (Grid BFS/DFS)

Count islands of '1's in a grid by flooding each one with BFS or iterative DFS in O(rows × cols). The most common graph question in FAANG interviews.

The problem

grid is a list of strings of '1' (land) and '0' (water). Land connects up, down, left and right (not diagonally). Return the number of islands.

Examples

  1. Example 1

    Input

    num_islands(['11110', '11010', '11000', '00000'])

    Expected output

    1
  2. Example 2

    Input

    num_islands(['11000', '11000', '00100', '00011'])

    Expected output

    3

+ 4 hidden tests on Submit — diagonals don't connect.

Edge cases to ask about

  • Empty grid
  • All water
  • Diagonal neighbours

Hints

0/3

    How an interviewer scores this

    0/9
    Python 3.13 · num_islands
    ⌘/Ctrl + Enter runs the examples

    Your code runs in real CPython inside your browser — nothing is sent anywhere. The first run downloads the interpreter (about 6 MB, once). Your code is saved on this device as you type.

    Complexity Lab

    What does this cost as n grows?

    Interviewers score the analysis as much as the code. Commit to an answer first — then check it, and measure your code against the optimal one at growing input sizes.

    Time complexity of the optimal solution
    Space complexity (extra memory)

    Pick both to reveal the answer.

    Measure it

    Runs the function on inputs of size 250 up to 16,000 and records the time and peak memory. Slow solutions stop early — a short curve is itself the answer.

    From brute force to optimal

    The progression an interviewer wants to hear, one step at a time.

    ApproachTimeSpaceIdea
    Recursive DFS flood fillO(R·C)O(R·C)Recursion depth can hit Python's limit on a big island.
    BFS with a queueO(R·C)O(R·C)Iterative — safe for any island size.
    bestUnion-FindO(R·C · α)O(R·C)Useful when land is added over time.
    Walkthrough of the optimal approach (try it yourself first)

    Scan every cell. When you meet unvisited land, count an island and flood-fill it — BFS or DFS over the 4 neighbours, marking cells as seen. Each cell is processed once, so O(rows × cols).

    Prefer an iterative BFS/DFS in Python: a recursive flood fill over a 1000 × 1000 island blows the recursion limit.

    Complexity: O(R·C) time, O(R·C) space. Every cell is visited a constant number of times; the seen-set and queue can hold every cell.

    Reveal the reference solution
    from collections import deque
    
    def num_islands(grid):
        if not grid:
            return 0
        rows, cols = len(grid), len(grid[0])
        seen = set()
        islands = 0
        for r in range(rows):
            for c in range(cols):
                if grid[r][c] == "1" and (r, c) not in seen:
                    islands += 1
                    seen.add((r, c))
                    queue = deque([(r, c)])
                    while queue:
                        y, x = queue.popleft()
                        for ny, nx in ((y + 1, x), (y - 1, x), (y, x + 1), (y, x - 1)):
                            if 0 <= ny < rows and 0 <= nx < cols and grid[ny][nx] == "1" and (ny, nx) not in seen:
                                seen.add((ny, nx))
                                queue.append((ny, nx))
        return islands

    Follow-ups interviewers ask

    • Max island area.
    • Islands appear one by one (Union-Find).

    Frequently asked interview questions

    Core interview concepts, complexities, and follow-ups scored by hiring teams.

    What is the time complexity of Number of Islands (Grid BFS/DFS) in Python?

    The optimal solution runs in O(R·C) time and O(R·C) auxiliary space. Every cell is visited a constant number of times; the seen-set and queue can hold every cell.

    What is the brute-force approach, and how do you optimise it?

    Recursive DFS flood fill: O(R·C) time, O(R·C) space. Recursion depth can hit Python's limit on a big island. BFS with a queue: O(R·C) time, O(R·C) space. Iterative — safe for any island size. Union-Find: O(R·C · α) time, O(R·C) space. Useful when land is added over time.

    What follow-up questions do interviewers ask about Number of Islands (Grid BFS/DFS)?

    Max island area. Islands appear one by one (Union-Find).