Pacific Atlantic Water Flow – Solution & Complexity

1. Recognize the Pattern

The key pattern is: Reverse graph searches grow inward from both oceans. Identify the state and invariant before coding.

2. Build the Algorithm

Advance one state transition at a time. Mark or update state before exploring dependent work.

3. Check Edge Cases

Test empty or minimal input, skewed shapes, duplicates where allowed, and impossible outcomes.

4. Solution and Complexity

Time: O(mn). Space: O(mn).

def pacific_atlantic(heights: list[list[int]]) -> list[list[int]]:
    rows, cols = len(heights), len(heights[0])
    def reach(starts):
        seen, stack = set(starts), list(starts)
        while stack:
            r, c = stack.pop()
            for dr, dc in ((1,0),(-1,0),(0,1),(0,-1)):
                nr, nc = r + dr, c + dc
                if 0 <= nr < rows and 0 <= nc < cols and (nr,nc) not in seen and heights[nr][nc] >= heights[r][c]:
                    seen.add((nr,nc)); stack.append((nr,nc))
        return seen
    pacific = reach([(0,c) for c in range(cols)] + [(r,0) for r in range(rows)])
    atlantic = reach([(rows-1,c) for c in range(cols)] + [(r,cols-1) for r in range(rows)])
    return [[r,c] for r in range(rows) for c in range(cols) if (r,c) in pacific & atlantic]

FAQ