← Back to DSA
#200
Number of Islands
Number of Islands solution for LeetCode 200, with the key idea, complexity breakdown, and working code in Java, C++, JavaScript, TypeScript, C, Go, and Rust.
Solve on LeetCode ↗Number of Islands
Why it belongs on this sheet
This is one of the most common graph and grid traversal problems in interview prep.
Pattern
Connected component counting
Approach
Scan the grid. Whenever you find unvisited land, increment the island count and run DFS to mark that whole component as visited.
Java solution
class Solution {
public int numIslands(char[][] grid) {
int islands = 0;
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[0].length; col++) {
if (grid[row][col] == '1') {
islands++;
sink(grid, row, col);
}
}
}
return islands;
}
private void sink(char[][] grid, int row, int col) {
if (
row < 0 || col < 0 || row == grid.length || col == grid[0].length
|| grid[row][col] != '1'
) {
return;
}
grid[row][col] = '0';
sink(grid, row + 1, col);
sink(grid, row - 1, col);
sink(grid, row, col + 1);
sink(grid, row, col - 1);
}
}
Complexity
- Time:
O(m * n) - Space:
O(m * n)in the worst recursive case
Interview note
You can say "each land cell is visited once" as the main time-complexity argument.
Dynamic Programming
7 DP Patterns > 100 LeetCode Questions
Most DP questions are repeated ideas. Stop treating DP like chaos. Learn the 7 repeatable patterns that unlock most placement-level questions.
7 patternsProgress tracking
Read 7 patterns (5 min)