InterviewDryRun
Coding interview · Asked at mid and senior level

Number of Islands

How the interviewer asks it

“Given a grid of 0s and 1s, count the islands. An island is a group of 1s connected horizontally or vertically.”
Sample test input
4 5
11110
11010
11000
00000
Expected output
1

In the practice room your code reads the input from standard input, and Run checks it against tests like this one. Try it now in your browser, in Python or JavaScript.

Typed drills are free and unlimited: the AI scores your answer against the outline below.

What the interviewer is looking for

  • You see the grid as a graph and counting islands as counting connected components.
  • Correct bounds checks and a clear way to mark cells visited.
  • You mention that deep recursion can overflow the stack on a big grid and offer BFS or an explicit stack.
  • O(rows × cols) time with a short justification.

How to structure your answer

  1. 01

    Clarify

    Ask whether diagonals count, whether you may modify the grid, and how big it can get.

  2. 02

    Scan

    Loop over every cell. Each time you find an unvisited 1, add one to the count and flood fill from it.

  3. 03

    Flood fill

    DFS or BFS to the four neighbours, marking each land cell visited (or setting it to 0).

  4. 04

    Test

    An all-water grid, a single cell, and two islands touching only at a corner.

  5. 05

    Complexity

    O(rows × cols) time, and O(rows × cols) space in the worst case for the queue or recursion.

Best answers from candidates

No candidate answers yet. Type yours, and if it scores 6 or more you can show it here without your name.

Answers are shared by candidates, without names, after a privacy check. Add yours

Common mistakes

  • Marking cells visited when they are popped instead of when they are pushed, which queues the same cell many times in BFS.
  • Mixing up rows and columns in the bounds check.
  • Counting diagonal neighbours when the question said only four directions.

Follow-up questions to expect

  • The grid is 10^9 cells on disk. How would you count islands? (Process row strips and merge with union-find.)
  • Return the size of the largest island.
  • Land is added one cell at a time; report the count after each addition.

Now answer it out loud

Max will ask you this exact question, listen to your answer, push on the weak spots with follow-ups like the ones above, and score you when you finish.

Practice with Max

Free: a 5-minute voice round and unlimited typed drills, with scored feedback. No card, and your camera is never recorded.

More coding interview questions

Preparing for this round? Read how to prepare for a coding interview: a four-week DSA plan.