Pacific Atlantic Water Flow

Medium

Question

You're given a 2D array that shows a bird's-eye view of a mountain. Each cell holds the height of that spot of land. The mountain sits on an island with oceans all around it. The Pacific Ocean touches the top and left edges. The Atlantic Ocean touches the bottom and right edges.

When it rains, water can flow north, south, east, or west. It can only flow to land that's the same height or lower.

Return a list of the coordinates of every cell where rainwater can flow to both the Pacific and the Atlantic.

Pacific Atlantic Water Flow Example 1

Input: heights = [[2, 2, 3], [6, 7, 2], [8, 7, 1]]

Output: [(0, 2), (1, 1), (2, 0), (2, 1)]

Water at every coordinate in the result list can reach both the Pacific Ocean and the Atlantic Ocean.

For example...
  • water at (0, 2) = 3 can flow north into the Pacific, or east into the Atlantic
  • water at (1, 1) = 7 can flow west > west into the Pacific, or east > south > east into the Atlantic
  • water at (2, 1) = 7 can flow north > north > west > west into the Pacific, or south into the Atlantic
Note: Water can take more than one path from each of these coordinates. These are just a few examples.
Pacific Atlantic Water Flow Example 2

Input: heights = [[2, 1], [1, 3]]

Output: [(0, 0), (0, 1), (1, 0), (1, 1)]

Water from every spot on the mountain can reach both the Pacific and the Atlantic.

For example...
  • water at (0, 0) = 2 can flow north into the Pacific, or east > east into the Atlantic
  • water at (1, 0) = 1 can flow west into the Pacific, or south into the Atlantic
  • water at (1, 1) = 3 can flow west > west into the Pacific, or south into the Atlantic
Pacific Atlantic Water Flow Example 3

Input: heights = [[1, 2, 3, 4], [1, 7, 3, 8], [3, 5, 1, 2], [8, 3, 1, 8]]

Output: [(0, 2), (0, 3), (1, 1), (1, 2), (1, 3), (2, 1), (3, 0)]

Water at each coordinate in the result list can reach both the Pacific and the Atlantic.

For example...
  • water at (1, 1) = 7 can flow north > north into the Pacific, or south > south > south into the Atlantic
  • water at (1, 2) = 3 can flow north > north into the Pacific, or south > south > south into the Atlantic
  • water at (2, 1) = 5 can flow west > west into the Pacific, or south > south into the Atlantic

Clarify the problem

What are some questions you'd ask an interviewer?

Understand the problem

What is the output for the following input? heights = [[5, 3], [2, 5]]
[(0, 0), (0, 1), (1, 0), (1, 1)]
[(0, 0), (1, 1)]
[(0, 0), (0, 1)]
[(0, 0), (1, 0)]

Remember to understand the problem and plan your approach before you start coding.