PPractick

DSA interview question

Number of Islands (4-Directional)

Medium · Data structures · Topics: graph, dfs, bfs, matrix

The problem

A satellite map is a grid of '1' (land) and '0' (water). An island is a group of land cells connected horizontally or vertically (diagonals don't count), and the edge of the map counts as water. Count the islands. Scan every cell, and when you hit land that hasn't been visited, that's a new island: flood-fill it with BFS or DFS over the four neighbours so its other cells aren't counted again.

Example: 11000 / 11000 / 00100 / 00011 → 3.

Function signature

int numIslands(vector<string> grid);

Test cases

Input (rows)OutputExplanation
11110 11010 11000 000001
11000 11000 00100 000113
101 010 1015Diagonals don't connect with 4 directions
11
00

(Confirm: connectivity is 4-directional only; the grid may be modified.)

How interviewers phrase it

Clarifying questions to ask

  1. 4 or 8 directions? (4.)
  2. May I modify the grid? (Yes: sink visited land to '0'.)
  3. How large? (Up to 300 × 300, so iterative BFS avoids deep recursion.)

Follow-ups to expect

  1. "How does this compare with the 8-directional version?"
  2. "No modifying the grid?"
  3. "DSU approach?"
  4. "Largest island, or island perimeter?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in