Blind 75
44 / 75Free practice

Pacific Atlantic Water Flow

Medium · Graphs

Jump to code

In a rectangular height grid, water may move to a horizontal or vertical neighbor of equal or lower height. Return cells that can reach both the top/left boundary and the bottom/right boundary.

Examples

Example 1

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]]

Output: [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]

Example 2

heights = [[1]]

Output: [[0,0]]

Constraints

  • 1 <= heights.length, heights[r].length <= 100
  • 0 <= heights[r][c] <= 1000
Need a hint?

Reverse the flow and start from each boundary.

Real graph interview questions

Questions on the same topic that candidates reported from real company interviews. Some company questions are locked and open with Premium or XP.

Browse all real coding interview questions

Accepted submissions mark this problem complete. Progress stays in this browser.

Run checks 5 examples. Submit checks all 9 cases. A free account runs this problem; no XP needed.
Language
Case 1
Input
[
  [
    [
      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
    ]
  ]
]
Expected
[
  [
    0,
    4
  ],
  [
    1,
    3
  ],
  [
    1,
    4
  ],
  [
    2,
    2
  ],
  [
    3,
    0
  ],
  [
    3,
    1
  ],
  [
    4,
    0
  ]
]
Case 2
Input
[
  [
    [
      1
    ]
  ]
]
Expected
[
  [
    0,
    0
  ]
]
Case 3
Input
[
  [
    [
      1,
      1
    ],
    [
      1,
      1
    ]
  ]
]
Expected
[
  [
    0,
    0
  ],
  [
    0,
    1
  ],
  [
    1,
    0
  ],
  [
    1,
    1
  ]
]
Case 4
Input
[
  [
    [
      1,
      2
    ],
    [
      3,
      4
    ]
  ]
]
Expected
[
  [
    0,
    1
  ],
  [
    1,
    0
  ],
  [
    1,
    1
  ]
]
Case 5
Input
[
  [
    [
      3,
      3,
      3
    ],
    [
      3,
      1,
      3
    ],
    [
      3,
      3,
      3
    ]
  ]
]
Expected
[
  [
    0,
    0
  ],
  [
    0,
    1
  ],
  [
    0,
    2
  ],
  [
    1,
    0
  ],
  [
    1,
    2
  ],
  [
    2,
    0
  ],
  [
    2,
    1
  ],
  [
    2,
    2
  ]
]

Drafts are saved per language in this browser when storage is available.