Skip to main content
mediumBlind 75

Pacific Atlantic Water Flow

Given an m x n matrix of heights Find all cells where water can flow to BOTH Pacific and Atlantic oceans Pacific touches left and top edges, Atlantic touches right and bottom Water flows from cell to adjacent cells with height <= current height Example: [[1,2,3],[4,5,6],[7,8,9]] => [[0,2],[1,2],[2,0],[2,1],[2,2]]

Pacific Atlantic Water Flow is a traversal problem: the hard part is modeling the state you visit. Interviewers love it because it reveals your traversal modeling and your edge-case discipline. Be clear about what a state is; that's the difference between BFS/DFS working or blowing up.

Examples

You write

pacific_atlantic(heights: List[List[int]])

  1. Example 1

    Input
    heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]]
    returns
    [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]
  2. Example 2

    Input
    heights = [[1]]
    returns
    [[0,0]]

The pattern behind it

Arrays & Hashing

I reach for it when

  • You catch yourself scanning the array again for every element.
  • The problem asks about duplicates, pairs, counts or groups.

Say this before you type. Say what the key is and what the value remembers, before you write the loop.

All 127 Arrays & Hashing problems

Graphs

I reach for it when

  • The input is edges, prerequisites or connections.
  • You need cycles, an ordering or connected groups.

Say this before you type. Say whether the edges are directed, and which of the three jobs you are doing.

All 32 Graphs problems

Meet Coco

Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.

1Find Pacific Atlantic Water Flowmedium
2Part 2
3Part 3

Each locked part opens in the editor once the part before it passes.