Trapping Rain Water

Quick Overview

Given elevation map, compute how much water it can trap after raining. Tests two-pointer technique with careful logic.

ByteDance
Coding & Algorithms
Software Engineer
ByteDance
Software Engineer
Technical Screen
Coding & Algorithms
Hard

12


Given elevation map, compute how much water it can trap after raining. Tests two-pointer technique with careful logic.

Two-pointer problems are a staple at ByteDance. This classic hard problem tests precise reasoning about invariants.

What the Interviewer Expects
  • Implement the two-pointer O(n) solution
  • Explain the invariant that makes the two-pointer approach work
  • Handle edge cases (flat terrain, single bar, descending/ascending)
  • Discuss alternative approaches (stack-based, DP with prefix max)
  • Achieve O(1) space with two pointers
Key Topics to Cover
Two pointers
Array manipulation
Invariants
Water trapping
Space optimization
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 extend this to 2D (trapping rain water on a grid)?
  • What if the bars have different widths?
  • Can you visualize which bars contribute to trapping at each position?
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 is a list of non-negative integers height, each a bar of width 1. Return the total units of water trapped after rain. Clarify: heights are integers, the list may be empty, and water spills off...

High-Level Design

Water above index i equals min(max height to the left, max height to the right) - height[i], clamped at zero. A prefix-max and suffix-max array gives O(n) time and O(n) space. Two pointers remove ...


Submit Your Answer
Markdown supported

Related Questions