LeetCode 42: Trapping Rain Water is a Hard array / string problem. This Python walkthrough develops a two pointers with bounded sides solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.
This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.
| Difficulty | Hard |
|---|---|
| Topic | Array / String |
| Reusable pattern | two pointers with bounded sides |
| Complexity | O(n) time and O(1) extra space |
Recognizing the pattern
Array and string questions usually reward a precise index invariant. Decide which prefix or suffix is already final before mutating the next position.
For this problem specifically, move the side with the lower current maximum. That lower boundary already determines how much water can be trapped at its pointer. The invariant worth writing beside the code is: Processed positions have their final water amount because their limiting boundary is known.
Step-by-step algorithm
- Identify the input state consumed by
trap(height)and initialize the data required by the two pointers with bounded sides pattern. - Move the side with the lower current maximum. That lower boundary already determines how much water can be trapped at its pointer.
- After each update, verify the page’s central invariant: Processed positions have their final water amount because their limiting boundary is known.
- Finish only after the boundary behavior is covered: Fewer than three bars trap nothing; equal-height walls are handled by either side.
Python solution
class Solution:
def trap(self, height):
left, right = 0, len(height) - 1
left_max = right_max = water = 0
while left <= right:
if left_max <= right_max:
left_max = max(left_max, height[left])
water += left_max - height[left]
left += 1
else:
right_max = max(right_max, height[right])
water += right_max - height[right]
right -= 1
return waterReading the implementation
The main entry point is trap(height). The named working state includes left, left_max, water, right_max; those variables make the two pointers with bounded sides state visible instead of hiding it in incidental control flow.
A single main loop advances the algorithm, which is the key reason the traversal does not revisit already resolved input unnecessarily. In concrete terms, move the side with the lower current maximum. That lower boundary already determines how much water can be trapped at its pointer.
Correctness argument
Initialization. The data structure starts with exactly the information known before any input element is processed.
Preservation. Move the side with the lower current maximum. That lower boundary already determines how much water can be trapped at its pointer. Each update records the current item without invalidating earlier decisions; consequently, processed positions have their final water amount because their limiting boundary is known.
Termination. The traversal consumes a finite input or finite state space. At the end, the invariant covers the complete input, which is precisely the condition required for the returned result.
Complexity and trade-offs
O(n) time and O(1) extra space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.
A copied output buffer can simplify reasoning, but the in-place version reduces auxiliary memory when mutation is allowed. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.
Regression check
The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.
One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.
assert Solution().trap([0,1,0,2,1,0,1,3,2,1,2,1]) == 6Common mistakes and edge cases
- Problem-specific boundary: Fewer than three bars trap nothing; equal-height walls are handled by either side.
- Pattern-level pitfall: Do not let a write operation destroy input that a later read still needs; write direction and boundary conventions matter.
- Invariant check: after every update, confirm that processed positions have their final water amount because their limiting boundary is known.
Interview review checklist
- Explain why two pointers with bounded sides matches the structure of this input.
- State the invariant in one sentence before tracing code: Processed positions have their final water amount because their limiting boundary is known.
- Derive O(n) time and O(1) extra space from how many times each element or state is visited.
- Test the boundary explicitly: Fewer than three bars trap nothing; equal-height walls are handled by either side.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 135. Candy · Next: 13. Roman to Integer