Max Area of Island

mediumTests passed 2026-11-11v1.0.0

1. Core Invariant / The Trick

DFS returns exact area contributed by a connected component (`1 + sum(4 neighbors)`), sinking `1 -> 0` upon arrival so each cell counts once.

2. Complexity Bounds & Proof

Every land cell flips to water once; DFS stack is bounded by total cells.

3. Minimal Idiomatic Code

def maxAreaOfIsland(grid: list[list[int]]) -> int:
    R, C = len(grid), len(grid[0])
    def dfs(r: int, c: int) -> int:
        if not (0 <= r < R and 0 <= c < C and grid[r][c] == 1):
            return 0
        grid[r][c] = 0
        return 1 + dfs(r + 1, c) + dfs(r - 1, c) + dfs(r, c + 1) + dfs(r, c - 1)
    return max((dfs(r, c) for r in range(R) for c in range(C) if grid[r][c] == 1), default=0)

4. Failure Modes & Interview Follow-ups

Pitfalls:- Forgetting all-water grids return `0` cleanly when `best = 0`. - Mutating grid only if caller allows; otherwise keep a `visited` boolean matrix.
Follow-ups:- Making a Large Island (flip one `0 -> 1`): label each island ID -> area, then probe each `0` cell summing unique neighbor island IDs + 1.

Personal Notes & Scratchpad (Local-First Yjs CRDT)

Saved instantaneously in IndexedDB. Streams live across peers via Hocuspocus when signed in.

Related Invariants

Browser Scratchpad
Console Output
Click Run or press Cmd/Ctrl+Enter to execute locally in a Web Worker.