Number of Islands

Python data engineering interview problem. Difficulty: advanced. Pattern: Graphs. About 18 minutes. Part of the Pro drill bank.

Count islands of '1' in a grid of '1'/'0'. Treat this as a production helper: match the contracted return shape, including empty and duplicate inputs.

A grid of land and water can represent connected regions in a data map. One island is a group of land cells connected up, down, left or right. Count the connected groups of '1' cells. Once a land cell is visited, mark its whole connected component so it is not counted again. Write num_islands(grid: list) -> int. The sample has one group at the top left and one isolated land cell at the bottom right, so the answer is 2. The starter file already has the function name and harness print lines. Keep them and fill only the function body.

Requirements

  • Visit four-directional neighbours only.
  • Count an island once, even when it has many cells.
  • Return the number of islands as an integer.

Constraints

  • Cells are strings '1' and '0', and the grid may be empty.
  • Diagonal contact does not connect two islands.

Examples

Input: num_islands([['1','1','0'],['1','0','0'],['0','0','1']]) Output: 2 Two connected components of land.

Topics: lakebench, python, dfs, grid.

More Python interview questions · All interview problems · Learn data engineering

advanced

Number of Islands

Interview-style drill: Count islands of '1' in a grid of '1'/'0'.

Implement `num_islands(grid: list) -> int` where grid cells are `'1'` (land) or `'0'` (water). Example: `[['1','1','0'],['1','0','0'],['0','0','1']]` → `2`. Keep the harness.