IntermediateGraphsArrays

Number of Islands

Problem

Given an m × n grid of characters where '1' represents land and '0' represents water, return the number of islands. An island is a maximal group of land cells connected horizontally or vertically (not diagonally). You may assume the grid is surrounded by water.

Constraints
  • 1 ≤ m, n ≤ 300
  • grid[i][j] is '0' or '1'
Examples
in: grid = [["1","1","0"],["0","1","0"],["0","0","1"]]
out: 2
The three 1s at top-left connect; the bottom-right 1 is separate.
in: grid = [["0","0"],["0","0"]]
out: 0

What this tests

  • Seeing a grid as an implicit graph
  • Connected components via flood fill (BFS or DFS)
  • Marking visited cells (in place vs a separate set)
  • Recursion depth awareness on large grids
  • Union-find as the alternative for dynamic/streaming variants
Pattern RecognitionImplementationEdge CasesComplexity AnalysisCommunication

Progressive hints

Choose how much help you want. Each hint reveals a little more; the pattern is not named until hint 2.

Hint 1Direction
Hint 2Pattern
Hint 3Data structure
Hint 4Algorithm
Hint 5Pseudocode
Solution

Solve in your language

The editor, starter code and solution adapt to the language you pick — C++, JavaScript, TypeScript or Python.

Solve in

Candidate thinking

How a strong candidate reasons through this problem, step by step.

Try the problem yourself first (or run the mock interview), then compare your process against a strong candidate's.

Follow-up engine

Requirements change; so does the right algorithm.

F1
Land cells are added one at a time and after each addition you must report the island count (Number of Islands II).
F2
Return the size of the largest island.
F3
The grid does not fit in memory and arrives row by row.
F4
Count islands that do not touch the border, or count distinct island shapes.

Related concepts