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
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
grid = [
[1,1,0,0,1],
[1,0,0,1,1],
[0,0,0,0,0],
[0,1,1,0,1]
]Output4Two islands along the top, a pair of cells in the bottom row, and a single cell in the bottom-right corner.
Example 2
grid = [[1,0],[0,1]]Output2Cells 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 questionMore coding questions
- Merge Intervals · Medium
- LRU Cache · Medium
- Two Sum · Easy
- Valid Parentheses · Easy
- Longest Substring Without Repeating Characters · Medium
- Top K Frequent Elements · Medium
More on these rounds: Coding interview practice.