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
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
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- 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 ProblemsSample 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 ...