Back to Practice Dashboard
Top 150 InterviewEasy
Number of Islands
Learn how to solve the 'Number of Islands' problem. This detailed resource details brute force and optimized approaches.
Problem Statement
Easy
Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.
An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Write a function numIslands(grid: List[List[str]]) -> int.
Constraints
- •m == len(grid)
- •n == len(grid[i])
- •1 <= m, n <= 300
- •grid[i][j] is '0' or '1'
Examples
Example 1
Input
grid = [["1","1","1","1","0"],["1","1","0","1","0"],["1","1","0","0","0"],["0","0","0","0","0"]]
Output
1
Explanation
There is a single island consisting of all connected '1's starting from top-left.
Example 2
Input
grid = [["1","1","0","0","0"],["1","1","0","0","0"],["0","0","1","0","0"],["0","0","0","1","1"]]
Output
3
Explanation
There are three distinct islands separated by '0's.
Need a Hint?
Represent graph node connections as an adjacency list/matrix, then use standard BFS or DFS graph traversal.
Edge Cases to Watch
- Empty list or null input variables
- Single item lists/arrays
- Extremely large input bounds causing integer or stack overflow
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.