Trapping Rain Water: The O(1) Two-Pointer Solution That Wins Interviews
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.
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.
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.