Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Graphs

Count the islands in a grid

Easy · Target 12 minutes · Graphs · Type asked atAmazonBloombergMeta

A grid is given as a list of equal-length strings of '1' (land) and '0' (water). Two land cells belong to the same island if they share an edge: up, down, left or right, not diagonally. Return the number of islands.

Examples

InputOutputWhy
grid = ["11000", "11000", "00100", "00011"]3A 2 × 2 block, a single cell, and a pair.
grid = ["101", "010", "101"]5Diagonal neighbours do not connect: five islands of one cell.
grid = ["000"]0No land at all.

Constraints

  • 1 ≤ rows, cols ≤ 300
  • Every row has the same length
  • Cells are '0' or '1'

Hints

Hint 1

Treat each land cell as a node with up to four neighbours. An island is a connected component.

Hint 2

Scan the grid. When you meet land you have not seen, you have found a new island: count it.

Hint 3

Then visit every cell of that island (depth-first or breadth-first) and mark it seen, so the scan never counts it again.

Where people lose marks

  • Treating diagonal cells as neighbours. "5" in the second example becomes "1".
  • Recursive flood fill on a large grid: Python stops at depth 1,000 and other languages overflow the stack.
  • Marking a cell when it is popped rather than when it is pushed, so the same cell is pushed several times and the search slows down badly.
  • Modifying the input grid to mark cells, when the interviewer asked you not to. Keep a separate seen table, or ask first.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.