Find Cells Whose Rainfall Drains to Both Western and Eastern Coasts

Last updated: November 29, 2026

Quick Overview

Given a height grid where the top and left edges border the western ocean and the bottom and right edges border the eastern ocean, return all cells from which water can flow to both oceans, moving to neighbors of equal or lower height.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Medium

0

0

0 solved


Given a height grid where the top and left edges border the western ocean and the bottom and right edges border the eastern ocean, return all cells from which water can flow to both oceans, moving to neighbors of equal or lower height.

An onsite question in the spirit of terrain analysis for Google Earth or Maps flood layers. The interviewer is checking whether you reverse the search direction: instead of simulating water from every cell, you climb uphill from each ocean once.

What the Interviewer Expects
  • Recognize that searching from each cell is O((RC)^2)
  • Reverse the flow and search uphill from each coast
  • Run two multi-source traversals and intersect
  • Use the non-decreasing condition correctly in reverse
  • Return coordinates in a clear format
Key Topics to Cover
multi-source BFS
reverse search
grid
set intersection
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • What if water can also flow diagonally?
  • Return only the cells that drain to exactly one ocean.
  • How would you handle a grid too large for memory, tiled across machines?
  • What if heights update in a few cells?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements
  • Input: heights R by C.
  • Water moves to a 4-neighbor with height less than or equal to the current height.
  • West ocean touches row 0 and column 0; east ocean touches the last row and last column....
High-Level Design

The naive approach launches a search from every cell, which is O((RC)2)O((RC)^2). Flip the direction: a cell drains to the west ocean exactly when there is a path from the west coast to it that never goes d...


Submit Your Answer
Markdown supported