DSA With AI
Week 5 ยท Graphs

Number of Islands

Solve Number of Islands by recognizing the Graphs pattern and turning the prompt into a small invariant before coding.

Medium Graphs Week 5 Practice runner

Frame the problem

  • Implement num_islands with the exact signature used by the interactive runner.
  • Use the visible tests to confirm the input and output shape before reading the final solution.
  • Treat challenge tests as edge-case pressure: empty inputs, repeated values, boundary shapes, or impossible states.
  • State the invariant before code, then dry-run one passing case and one failing-looking case.
1. Reveal example inputs and outputs

Example 1

Input:

num_islands([
  [
    "1",
    "1",
    "1",
    "1",
    "0"
  ],
  [
    "1",
    "1",
    "0",
    "1",
    "0"
  ],
  [
    "1",
    "1",
    "0",
    "0",
    "0"
  ],
  [
    "0",
    "0",
    "0",
    "0",
    "0"
  ]
])

Output:

1
2. Brute force first

What direct brute force would be correct for a tiny input? Name the exact repeated work that the target pattern removes.

3. Reveal the insight ladder
  1. Map the prompt to the Graphs pattern instead of starting from syntax.
  2. Start DFS/BFS only from unvisited land.
  3. Diagonal land does not connect islands in this problem.
  4. Only reveal the final code after you can explain why each state update is safe.
4. Dry run before code
  1. islands-one: input [[["1","1","1","1","0"],["1","1","0","1","0"],["1","1","0","0","0"],["0","0","0","0","0"]]] should produce 1. Hint to check your state: Start DFS/BFS only from unvisited land.
  2. islands-three: input [[["1","1","0","0","0"],["1","1","0","0","0"],["0","0","1","0","0"],["0","0","0","1","1"]]] should produce 3. Hint to check your state: Diagonal land does not connect islands in this problem.
5. Reveal final Python solution
def num_islands(grid: list[list[str]]) -> int:
    if not grid:
        return 0

    rows, cols = len(grid), len(grid[0])
    seen: set[tuple[int, int]] = set()

    def dfs(row: int, col: int) -> None:
        if row < 0 or row == rows or col < 0 or col == cols or grid[row][col] != "1" or (row, col) in seen:
            return
        seen.add((row, col))
        dfs(row + 1, col)
        dfs(row - 1, col)
        dfs(row, col + 1)
        dfs(row, col - 1)

    count = 0
    for row in range(rows):
        for col in range(cols):
            if grid[row][col] == "1" and (row, col) not in seen:
                count += 1
                dfs(row, col)
    return count

Complexity: Derive the exact bounds from num_islands: count how often each input item is visited and the maximum size of the main state structure.

Interview narration

  • I will first describe the invariant in plain language.
  • Then I will explain what data structure carries that invariant across the traversal, loop, recursion, or DP transition.
  • Finally I will walk one edge case before writing the optimized version.

Common traps

  • Solving only the visible example instead of the invariant.
  • Forgetting empty input, singleton input, duplicate values, or impossible-state cases.
  • Revealing the solution before doing a dry run from the starter signature.

Follow-up drills

1. How do you turn this into a timed interview answer?

Start with the invariant, give the brute force in one sentence, name the optimized state, code the core loop or recursion, and run one visible test aloud before mentioning complexity.

2. How do you scale the same pattern to a larger input?

Track which state grows with the input: hash maps and sets grow with distinct values, queues grow with frontier width, recursion grows with depth, heaps grow with active candidates, and DP tables grow with state count.

3. What should you practice from blank tomorrow?

Rewrite num_islands without looking at the solution, then compare only the invariant and state updates before checking syntax.

Interactive runner

Write the required Python function. Your code runs locally in this browser. Hints reveal one failing case at a time.