interviewmind

Number of Islands

Number of Islands is a medium coding interview question. You’re given an m by n grid where each cell is 1 for land or 0 for water. Return the number of islands. Below are examples, the constraints and 3 hints; press Practice and Dana, the interviewer, asks it out loud while you answer in TypeScript, Python, Java, C++ or Go.

Updated · By InterviewMind

Practice this question

Free in your browser, no account.

The problem

Coding · Medium

You’re given an m by n grid where each cell is 1 for land or 0 for water. Return the number of islands.

An island is a group of land cells connected horizontally or vertically, never diagonally. Everything beyond the grid’s edges is water.

Example 1

Inputgrid = [ [1,1,0,0,1], [1,0,0,1,1], [0,0,0,0,0], [0,1,1,0,1] ]Output4

Two islands along the top, a pair of cells in the bottom row, and a single cell in the bottom-right corner.

Example 2

Inputgrid = [[1,0],[0,1]]Output2

Cells that touch only at a corner aren’t connected.

Constraints

  • 1 ≤ m, n ≤ 300
  • grid[i][j] is 0 or 1

Hints

Open one at a time, and try the question again after each.

Hint 1

Scan the grid cell by cell. Each time you reach land you haven’t visited yet, you’ve found a new island, so count it.

Hint 2

From that cell, visit the whole island with a depth-first or breadth-first search over the four cells around each one, marking land as visited, or turning it to water, so the scan never counts it again.

Hint 3

Check the bounds before you look at a cell, and skip diagonals. A 300 by 300 grid of all land makes a recursive search 90,000 calls deep, so an explicit stack or queue is safer.

Practice it out loud

In the practice room Dana reads the question aloud in your browser’s own voice, with captions, and you answer in the editor beside it, in TypeScript, Python, Java, C++ or Go. It can look like LeetCode, HackerRank, CoderPad or Codility, so the screen is the one you’ll meet. It’s free and needs no account. Run the InterviewMind desktop app beside it and it hears the question the way it hears a real call, so you can see what it would show you in the live round.

Practice this question

More coding questions

interviewmind

Clarity under pressure.

Download for macOSWindows

On an Intel Mac? Download for Intel