Loading…
Number of Islands is a medium coding interview question covering graphs, depth-first search, arrays — the kind asked at FAANG (Facebook/Meta, Apple, Amazon, Netflix, Google) and AI-first companies like Anthropic, OpenAI, and Nvidia.
Given an m x n grid of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and formed by connecting adjacent land cells horizontally or vertically.
Example: grid = [["1","1","0"], ["1","1","0"], ["0","0","1"]] -> 2
Try it yourself first
In an interview you'd get about 25 minutes for a medium question. Sketch an approach before peeking — struggling is where the learning happens.
Stuck? Reveal them one at a time — each hint gives away a little more.
Ready to compare notes? The full solution, visualization, and complexity analysis are below.
Flood-fill with DFS or BFS. Each time a '1' is encountered, increment the island count and recursively mark all connected land cells as visited by changing them to '0'. Time is O(m·n) because each cell is visited at most once.
| 1 | def num_islands(grid: list[list[str]]) -> int: |
| 2 | if not grid: return 0 |
| 3 | rows, cols = len(grid), len(grid[0]) |
| 4 | count = 0 |
| 5 | |
| 6 | def dfs(r, c): |
| 7 | if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1': |
| 8 | return |
| 9 | grid[r][c] = '0' # mark visited |
| 10 | dfs(r+1, c); dfs(r-1, c) |
| 11 | dfs(r, c+1); dfs(r, c-1) |
| 12 | |
| ▶ | for r in range(rows): |
| ▶ | for c in range(cols): |
| ▶ | if grid[r][c] == '1': |
| ▶ | count += 1 |
| ▶ | dfs(r, c) |
| 18 | return count |
Scan grid. Find '1' at (0,0). count=1. DFS floods this island.
Key Insights
A full interview loop is more than one round. These are the others, each with what is on the site for it.