Number of Islands
Quick Overview
Given a 2D grid of '1's (land) and '0's (water), count the number of islands. Tests BFS/DFS on grids, one of Google's most frequently asked problems.
0
Given a 2D grid of '1's (land) and '0's (water), count the number of islands. Tests BFS/DFS on grids, one of Google's most frequently asked problems.
Google often uses this in phone screens and early onsite coding rounds as a check on graph traversal fundamentals. The interviewer looks for a clean DFS or BFS over a grid, correct handling of boundaries and visited cells, and a clear complexity analysis.
What the Interviewer Expects
- Model the grid as an implicit graph of four-directionally adjacent land cells
- Implement DFS or BFS that marks visited cells exactly once
- Handle boundaries and empty grids correctly
- State O(M * N) time and discuss recursion depth versus an explicit stack
- Walk through a small example to verify the count
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- How would you avoid recursion depth limits on a very large grid?
- How would you solve it if the grid cannot be modified in place?
- How would you count islands as land cells are added one at a time?
- What changes if diagonal neighbors also count as connected?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Problem Analysis
The problem of counting the number of islands in a 2D grid is best solved using Depth-First Search (DFS) or Breadth-First Search (BFS). Here, the grid is composed of '1's representing land and '0's re...
Approach
- Initialize a counter to track the number of islands.
- Iterate through each cell in the 2D grid.
- When a '1' is found, increment the island counter.
- Perform a DFS or BFS from that cell to vis...