Find Terrain Cells Whose Runoff Reaches Both Coastlines

Last updated: November 29, 2026

Quick Overview

A height map grid has a west coast along its left and top edges and an east coast along its right and bottom edges. Water flows from a cell to a 4-neighbor of equal or lower height; return all cells from which water can reach both coasts.

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

0

0

0 solved


A height map grid has a west coast along its left and top edges and an east coast along its right and bottom edges. Water flows from a cell to a 4-neighbor of equal or lower height; return all cells from which water can reach both coasts.

This reverse-search grid problem appears in the style of Meta's onsite coding rounds, here with a terrain framing like the map data used by Meta's mapping and AR teams. The interviewer is checking whether you flip the direction and search uphill from each coast instead of simulating water from every cell.

What the Interviewer Expects
  • Notices forward search from every cell is O((RC)^2)
  • Runs reverse BFS or DFS from each coast, moving to higher or equal cells
  • Intersects the two reachable sets
  • Handles corner cells that touch both coasts
  • Uses iterative traversal for large grids
Key Topics to Cover
BFS
Reverse search
Grids
Graphs
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
  • How would you count cells reaching exactly one coast?
  • What if flow is allowed in eight directions?
  • How would you handle the grid if it were too large for memory?
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: integer grid h of size R x C. Output: list of [r, c] cells that can reach both coasts, in row-major order. West coast is row 0 and column 0; east coast is row R-1 and column C-1. Grids up t...

High-Level Design

Water flows downhill, so reverse it: starting from all cells on a coast, walk to neighbors whose height is greater than or equal to the current cell. Everything reached can drain to that coast. Do thi...


Submit Your Answer
Markdown supported