Skip to main content
← Problem catalogue Understand the pattern. Try it yourself. Review the solution. Practice this pattern →
Medium Queue / BFS High frequency Solution Available Practice Mode

Number of Islands LeetCode Solution

Tags: #Array #DFS #BFS #Matrix #Union Find

Approach Summary

DFS/BFS from each unvisited land cell, marking all connected land as visited. Count how many times you start a DFS.

Practice Mode 2 Progressive Approaches

Solve it yourself before revealing the code

DSA interviews test reasoning from brute force to optimal. Think through the constraints first.

Algorithmic Pattern

Master the Queue / BFS Pattern

View Pattern Guide →

Study the core invariant, step-by-step decision framework, and common interview traps for the Queue / BFS pattern.

Framework: Queue / BFS • Interview Prep: Tested at FAANG • Explore all Queue / BFS problems & invariants →

How to Recognize This Pattern

  • Count connected components in grid
  • Flood fill

Complexity Analysis

Time Complexity

O(m × n)

Space Complexity

O(m × n)

Tags

Array DFS BFS Matrix Union Find

Frequently Asked Questions

What is the optimal time and space complexity for Number of Islands?
The optimal solution for Number of Islands achieves O(m × n) runtime complexity and requires O(m × n) auxiliary space. Time Complexity is O(M * N) where M is the number of rows and N is the number of columns. Each cell in the grid is visited at most twice (once in the outer loops and once during the flood-fill). Space Complexity is O(M * N) in the worst case (e.g. a grid completely filled with land) for the DFS recursion stack or BFS queue.
How do I identify that Number of Islands requires the Queue / BFS pattern?
In technical interviews, look for key problem signals: Count connected components in grid; Flood fill. Recognizing these invariants allows you to bypass naive brute-force exhaustive search in favor of Queue / BFS strategy.
What critical edge cases must be handled in Number of Islands?
Essential edge cases to verify include: Empty grid or grid with empty rows — return 0; All water ('0') — no islands found, return 0; All land ('1') — single giant island, return 1; Diagonal land cells — diagonal connections do NOT form an island in 4-directional connectivity. Always walk through these scenarios with your interviewer before coding.
Which tech companies frequently ask Number of Islands?
Number of Islands is a Medium-difficulty question tagged with high recurrence. It is actively asked in technical screening and onsite interview loops at Amazon, Google, Facebook, Microsoft.
Buy me a coffee
Daily Practice
0/0