跪拜 Guibai
← All articles
Backend · Java · LeetCode

Trapping Rain Water: The O(1) Two-Pointer Solution That Wins Interviews

By Rain的Java大神之路 ·
Read original on juejin.cn ↗ Google Translate ↗ Alt translation

The two-pointer solution compresses two O(n) arrays down to two variables, giving O(1) extra space with no backtracking, and the interview script shows how to communicate that optimization chain convincingly. For developers interviewing at Chinese tech giants, this is a practical roadmap to turn a common algorithm question into a clear signal of engineering judgment.

Summary

LeetCode 42 appears constantly in Chinese big-tech interviews, and not because it requires memorization. The problem exposes a candidate's modeling ability, optimization instinct, edge-case handling, and communication in about fifteen minutes. A step-by-step progression from O(n²) brute force to O(n) DP to the O(1) space two-pointer solution demonstrates the optimization chain interviewers expect.

The core is the barrel effect: water at each index equals max(min(leftMax, rightMax) - height[i], 0). The two-pointer solution exploits the loop invariant that the shorter side's water level is locked once you know which side is shorter, so you can settle and advance without global information. Alternatives include a monotonic stack that computes water row by row and naturally supports streaming data.

Practical interview guidance covers common pitfalls like storing heights instead of indices in the stack, forgetting null or n<3 guards, and integer overflow in the total. Follow-up questions span LeetCode 11, the 2D version with min-heap plus BFS, parallel divide-and-conquer, and the O(n) theoretical lower bound.

Takeaways
— water[i] = max(min(leftMax, rightMax) - height[i], 0) is the core formula; all solutions compute this differently.
— Brute force scans left and right for each index, O(n²) time and O(1) space; it is only for explaining the principle.
— Dynamic programming precomputes leftMax and rightMax arrays, reaching O(n) time but O(n) space.
— The two-pointer solution only needs two max variables: the shorter side's water level is determined immediately, so you settle and move that pointer.
— Two-pointer loop condition must be left < right; using <= double-counts the meeting point.
— The monotonic stack stores indices, not heights, and computes width as i - left - 1; break if the stack becomes empty after popping.
— Guard against null and n < 3; use long accumulation in engineering because total water can exceed Integer.MAX_VALUE.
— LC 407 (2D trapping rain water) requires a min-heap plus BFS to peel the onion from the outermost boundary.
— O(n) is the theoretical time lower bound; every bar must be visited at least once.
— The recommended interview flow: restate boundaries, derive brute force, then DP, then two-pointer, and run explicit test cases.
Conclusions

The article's real value is the interview meta-skill: showing the optimization chain aloud matters more than instantly producing the optimal code.

The loop invariant argument for the two-pointer solution is compact enough to teach in interviews, and it cleanly explains why the shorter side can be settled without global information.

The monotonic stack is often overlooked, but the author correctly positions it as the answer for streaming or non-random-access data, which most candidates miss.

The 60-second recitation version and the memorized closing script are practical crutches that turn a coding problem into a rehearsed performance; interviewers may appreciate the structure, though some may see it as rote.

The emphasis on overflow and boundary guards signals the gap between algorithm puzzle solvers and engineers who ship production code.

Concepts & terms
Barrel effect (short-board effect)
The amount a container can hold is limited by its shortest side; in trapping rain water, the water level at each position is capped by the shorter of the maximum heights to the left and right.
Loop invariant
A property that remains true during every iteration of a loop. In the two-pointer solution, the invariant is that the current side being settled is the shorter one, so its water level is already determined by the max on that side.
Monotonic stack
A stack whose elements maintain a monotonic (here decreasing) order. In trapping rain water, it stores bar indices and settles water row by row when a taller bar appears, handling streaming scenarios naturally.
Source: juejin.cn ↗ Google Translate ↗ Backup ↗