Topics/Matrices & Grids/Number of islands

Pattern

Number of islands

Number of islands is a reusable approach under Matrices & Grids. Once you recognize the shape of the input and the ask, this pattern gives you a standard plan instead of inventing a new algorithm from scratch.

Matrices & GridsPatternsPattern

When to use it

Reach for Number of islands when a matrices & grids problem matches the cues in this lesson — especially after you’ve ruled out a brute-force nested scan.

How it works

  1. Restate the Matrices & Grids problem in one sentence and name the constraint that Number of islands exploits.
  2. Sketch the invariant Number of islands maintains (what stays true after each step).
  3. Walk a tiny example by hand, writing the state after every update.
  4. Translate that walk into code in your interview language, then list edge cases.

Solution

Reference implementation in C#, Python, Java, JavaScript, and C++.

Exact solutionNumber of islands

Why interviewers care

Interviewers grade pattern recognition. Naming Number of islands early shows you can classify the problem inside Patterns.

Drill Number of islands with Matrices & Grids problems — filter the bank and solve 2–3 Easy/Medium items while saying the invariant out loud.

Watch-outs

  • !Row/col swap bugs
  • !Mutating input unexpectedly
  • !Boundary checks

Practice this

Related Matrices & Grids problems — open any one and apply Number of islands.

Search bank →

More under Matrices & Grids

← Back to Matrices & Grids lesson