跪拜 Guibai
← Back to the summary

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

LeetCode 42 "Trapping Rain Water": A Question Interviewers Never Tire Of, Explained Thoroughly from Brute Force to Two Pointers O(1)

Author: Rain的Java大神之路

A friend of mine practiced problems for three years and hit "Trapping Rain Water" in his Alibaba first interview. He wrote the two-pointer solution and the interviewer simply nodded and said "passed." This question appears at big tech companies with absurdly high frequency, but what it really tests is not memorization; it tests optimization thinking. This article explains the essence of the problem, four solutions, correctness proof, a pitfall checklist, and high-frequency follow-up questions all in one go. If you are preparing for interviews, I suggest you bookmark it before reading on.

1. Why Do Big Companies Love This Question?

image.png

Problem link: https://leetcode.cn/problems/trapping-rain-water/description/

Many people think Trapping Rain Water is a "memorize the solution" problem, which is the biggest misconception.

The reason it appears so often is not because it is hard, but because within fifteen minutes it can expose a person's algorithmic intuition, optimization awareness, and communication ability completely.

What the interviewer is really testing is these four things:

Dimension Specific manifestation
Modeling ability Can you abstract "trapping water" into "take the smaller of left and right max, then subtract"
Optimization thinking Can you step from O(n²) all the way to O(1) space
Edge case handling Empty array, fewer than 3 bars, all increasing/decreasing, all flat
Communication Can you explain clearly "why moving the shorter side is correct"

So when you see the problem, remember one thing: don't rush to write code. First restate the problem, then show the evolution of your thinking, and finally land the optimal solution. That is the rhythm the interviewer wants to hear.

2. Problem Statement and the Soul Formula: The Barrel Effect

The problem is short:

Given n non-negative integers representing bar heights (each with width 1), calculate how many units of water these bars can trap after rain.

Official example:

Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6

The bar height distribution looks like this:

image.png

Rainwater accumulates in the "grooves" formed by the bars. For example, at index 2, the height is 0, the highest on the left is 1, and the highest on the right is 2, so it can hold 1 unit of water; at index 5, the height is 0, the highest on the left is 2, the highest on the right is 3, so it can hold 2 units.

The water level at each position is determined by the shorter of the highest bar on the left and the highest bar on the right, which is the barrel effect: water will not overflow above the shorter board.

water[i] = max( min(leftMax, rightMax) - height[i], 0 )

This formula is the soul of the entire problem. The four solutions below are essentially just different ways to compute it.

Compute it manually on the example and you immediately get the feel:

index i 0 1 2 3 4 5 6 7 8 9 10 11
height 0 1 0 2 1 0 1 3 2 1 2 1
leftMax 0 1 1 2 2 2 2 3 3 3 3 3
rightMax 3 3 3 3 3 3 3 3 2 2 2 1
water 0 0 1 0 1 2 1 0 0 1 0 0

Sum: 1 + 1 + 2 + 1 + 1 = 6, which matches the official output.

By the way, this intuition shares the same origin as LeetCode 11 "Container With Most Water", both use two pointers and the short-board effect. The difference is that 11 asks for a single maximum area, while 42 sums over all grooves. We will expand on this in the follow-up section.

3. Solution Evolution: An Optimization Chain from O(n²) to O(1)

In an interview, don't immediately throw out the optimal solution. Showing your thought process first is a plus. The whole chain looks like this:

image.png

Comparing all four solutions at a glance:

Solution Core idea Time Space Interview role Use case
Brute force by column Scan left and right for each column to find max O(n²) O(1) Explain the principle, don't dwell Very small data
Dynamic programming Precompute leftMax / rightMax arrays O(n) O(n) Safe transitional plan When you need to reuse max arrays
Two pointers Settle the shorter side, compute as you go O(n) O(1) Main answer, optimal First choice for interviews and engineering
Monotonic stack Decreasing stack settles grooves by "row" O(n) O(n) Highlight, bonus Streaming data, no random access

Below we break down each one from simple to deep.

4. Solution 1: Brute Force, Use It to Understand the Principle, Not for Interviews

The idea is straightforward: for each column, scan left and right, find the two maximums, and apply the formula.

// Time O(n²) | Space O(1) | Just explain the idea in interviews
public int trap(int[] height) {
    int n = height.length, water = 0;
    for (int i = 1; i < n - 1; i++) {
        int leftMax = 0, rightMax = 0;
        for (int j = i; j >= 0; j--) leftMax = Math.max(leftMax, height[j]);
        for (int j = i; j < n; j++) rightMax = Math.max(rightMax, height[j]);
        water += Math.min(leftMax, rightMax) - height[i];
    }
    return water;
}

The problem is obvious: each position repeatedly scans its left and right intervals. At the problem's data scale, O(n²) times out directly. This is the starting point for optimization.

Interviewer perspective: "If you can think of brute force, it shows you understand the problem's essence, but we don't accept O(n²), continue optimizing."

So the value of brute force is to help you master the formula and lay the groundwork for optimization motivation. Mention it in one sentence in the interview.

5. Solution 2: Dynamic Programming - Classic Space for Time

Since each position needs left and right maximums, compute them in advance and store them, then just look them up when needed.

Two recurrence relations:

leftMax[i]  = max(leftMax[i-1],  height[i])   // scan left to right
rightMax[i] = max(rightMax[i+1], height[i])   // scan right to left
public int trap(int[] height) {
    int n = height.length;
    if (n < 3) return 0;

    int[] leftMax = new int[n];
    int[] rightMax = new int[n];

    leftMax[0] = height[0];
    for (int i = 1; i < n; i++) {
        leftMax[i] = Math.max(leftMax[i - 1], height[i]);
    }

    rightMax[n - 1] = height[n - 1];
    for (int i = n - 2; i >= 0; i--) {
        rightMax[i] = Math.max(rightMax[i + 1], height[i]);
    }

    int water = 0;
    for (int i = 1; i < n - 1; i++) {
        water += Math.min(leftMax[i], rightMax[i]) - height[i];
    }
    return water;
}

Look back at the hand-computed table in section 2; the leftMax and rightMax rows are the two arrays this code preprocesses. After preprocessing, each position looks up in O(1), total time drops to O(n), and the logic is clear and bug-resistant.

The cost is two O(n) auxiliary arrays. At this point the interviewer will likely follow up:

"Can you save more space?"

Okay, the main character arrives.

6. Solution 3: Two Pointers - The Optimal Solution That Decides Your Fate

6.1 Key Insight: The Water Level on the Shorter Side Can Be Determined on the Spot

The difficulty with two pointers is: you only maintain two variables, leftMax and rightMax, with no global information. How dare you settle the water at the current position?

The answer is: you don't need global information, only need to know which side is shorter.

Take height[left] < height[right] as an example:

  1. On the right, there is at least a bar of height height[right] (the current right pointer position), which is taller than height[left];
  2. The left pointer has been moving forward, and each time it settles, it is the "shorter side", so leftMax will not exceed the maximum on the right;
  3. Therefore min(leftMax, rightMax) = leftMax - the water level at position left is locked by leftMax. Even if there are unvisited bars in between, they can only make the water level higher, not lower.

In technical terms, this is the loop invariant of two pointers: the short board determines the water level, and the long board just serves as the background.

The decision process each round:

image.png

6.2 Core Code (Recommended for Interviews)

class Solution {
    public int trap(int[] height) {
        // Boundary guard: fewer than 3 bars cannot form a groove, also prevents NPE
        if (height == null || height.length < 3) return 0;

        int left = 0, right = height.length - 1;
        int leftMax = 0, rightMax = 0;
        int water = 0;
        // In engineering, consider changing water to long: when n and heights are large, the sum can exceed int

        while (left < right) {
            if (height[left] < height[right]) {
                // left is the short board: water level only depends on leftMax
                leftMax = Math.max(leftMax, height[left]);
                water += leftMax - height[left];
                left++;
            } else {
                // right is the short board (including equality): water level only depends on rightMax
                rightMax = Math.max(rightMax, height[right]);
                water += rightMax - height[right];
                right--;
            }
        }
        return water;
    }
}

A few details worth noting:

Trace through the example to feel the rhythm of "settle the shorter side":

Step left right Comparison Action Accumulated water
1 0 11 h[0]=0 < h[11]=1 settle left, leftMax=0, +0 0
2 1 11 h[1]=1 >= h[11]=1 settle right, rightMax=1, +0 0
3 1 10 h[1]=1 < h[10]=2 settle left, leftMax=1, +0 0
4 2 10 h[2]=0 < h[10]=2 settle left, +1 1
5 3 10 h[3]=2 >= h[10]=2 settle right, rightMax=2, +0 1
... ... ... ... keep the rhythm of "settle the shorter side" ...
End 7 7 pointers meet stop 6

6.3 Technical Highlights, Mention Them Proactively in Interviews

Highlight one: space pushed to the limit. Compress two O(n) DP arrays into two variables, only 4 temporary variables total, O(1) extra space, cache-friendly.

Highlight two: monotonicity guarantees no backtracking. leftMax only increases as the pointer moves, each element is visited exactly once, time strictly O(n).

Highlight three: boundaries are naturally compatible. For an all-increasing array, the right pointer moves left the whole way and the trapped water is always 0; the same for all-decreasing and all-flat arrays, no extra branches needed.

Highlight four: overflow awareness. In engineering, when n is up to 210^5 and heights up to 10^5, the total water can reach 210^10, exceeding Integer.MAX_VALUE. Use long for accumulation and cast back at the end. Mentioning this proactively in an interview immediately sets you apart from those who memorized the solution.

If the interviewer asks "Can time be reduced further?", just answer: O(n) is the theoretical lower bound - each bar must be visited at least once. The real optimization space for this problem is in space complexity, and that is the thought process the interviewer really wants to see.

6.4 Two Equivalent Implementations, Pick One and Practice It

The two-pointer solution has two common style variants, both correct:

Style Condition Settlement Characteristic
Compare current bar heights height[l] < height[r] update max first, then settle Most common in interviews, intuitive to explain
Compare the two side maximums leftMax < rightMax max(leftMax - h[l], 0) as fallback Fewer branches, naturally handles boundaries

The second style looks like this:

while (left < right) {
    if (leftMax < rightMax) {
        totalRain += Math.max(leftMax - height[left], 0);
        leftMax = Math.max(leftMax, height[left]);
        left++;
    } else {
        totalRain += Math.max(rightMax - height[right], 0);
        rightMax = Math.max(rightMax, height[right]);
        right--;
    }
}

There is also a variant that checks before updating: first check if height[left] >= leftMax, if so update the left wall, otherwise settle the water. The logic is more direct, suitable for those who fear making mistakes.

The three styles are essentially equivalent. Pick one, practice it, don't mix them on the spot.

If you already feel you've learned something here, you can follow me - I keep dissecting high-frequency algorithm problems from big companies, no fluff, only practical stuff.

7. Solution 4: Monotonic Stack - Switch from "by Column" to "by Row"

The first three solutions compute water vertically by column. A monotonic stack changes the perspective: horizontally by row, like cutting a cake, settling one layer each time a groove appears.

Rule: maintain a decreasing stack (store indices), scan left to right. Once you encounter a bar taller than the stack top, the right wall of the groove has arrived, pop the stack top and settle.

image.png

public int trap(int[] height) {
    Deque<Integer> stack = new ArrayDeque<>(); // store indices! storing heights makes width impossible
    int water = 0;

    for (int i = 0; i < height.length; i++) {
        // encountering a bar taller than the stack top means the right wall appears, start settling
        while (!stack.isEmpty() && height[i] > height[stack.peek()]) {
            int bottom = stack.pop();          // groove bottom
            if (stack.isEmpty()) break;        // no left wall, can't hold water
            int left = stack.peek();           // groove left wall
            int w = i - left - 1;              // width
            int h = Math.min(height[left], height[i]) - height[bottom];
            water += w * h;                    // settle layer by layer horizontally
        }
        stack.push(i);
    }
    return water;
}

Three pitfalls, all learned the hard way:

A monotonic stack has unique value that two pointers can't provide - streaming scenarios:

"If the data comes in a stream and cannot be randomly accessed, I would use a monotonic stack, since it's a natural single-pass online algorithm; two pointers need to move from both ends inward, which requires random access."

Once you say this, the interviewer knows you aren't just reciting answers.

8. Pitfall Guide: 8 Traps Interviewers Love to Dig

# Pitfall Correct approach One-line response
1 Thinking the water level is determined by the "nearest taller bar" Water level depends on the global maximum on both sides: min(leftMax, rightMax) - h[i] "Essentially find the short board on each side"
2 Not knowing which to move when height[l] == height[r] Move the right pointer via else, doesn't affect correctness "Both versions pass"
3 Reversing the order of updating max and settling water Update first then settle, or check first then settle, keep the order consistent "Update first, difference is always non-negative"
4 Loop condition written as left <= right Use left < right, stop when they meet "Less-than prevents double counting"
5 Monotonic stack storing heights Store indices, width = i - left - 1 "Storing values makes width impossible"
6 No boundary guard Return 0 if null or length < 3 "Also prevents NPE"
7 Accumulation overflow Use long in engineering and cast at the end "nmaxH can reach 210^10"
8 Continuing after popping and the stack is empty No left wall, break directly "No left wall means no water"

9. High-Frequency Follow-up Questions: If You Answer These 6, You're Basically Safe

Follow-up Key points
Relationship with LeetCode 11 "Container With Most Water"? Same origin: two pointers and short-board effect; 11 finds a single maximum area (distance * shorter height), 42 sums all grooves and must maintain leftMax / rightMax instead of using current heights directly
How about 2D/3D versions? LeetCode 407, use min-heap + BFS: expand inward from the outermost ring, water level determined by the lowest known boundary, commonly called "peeling the onion"
Array too large for memory / streaming data? Switch to streaming monotonic stack: single-pass scan, only store groove indices, space is O(number of grooves) not O(n); for very large scenarios, external block sort
Can it be parallelized? Yes, divide and conquer: split by the highest bar into independent left/right subproblems; the global maximum is a natural water-level boundary, good for Fork/Join; DP prefix arrays can also be segmented and parallelized
Can time be below O(n)? No, each bar must be visited at least once, O(n) is the theoretical lower bound; the real optimization space is in O(n) to O(1) space
Used similar ideas in real work? Yes: available capacity calculation in monitoring systems, resource allocation in load balancing, big data stream processing, sliding windows; "two-pointer clamping" and "space for time" are common

For 407, remember one more thing: the 1D idea fails in 2D because water can flow away in all directions, so you must use a min-heap to "peel the onion" from the outermost ring inward, feeding water with the current lowest boundary.

10. Interview Rhythm and Script: Five-Step Method + 60-Second Recitation Version

The whole response can follow this rhythm:

image.png

The opening 30 seconds are especially crucial; proactively state the boundaries:

"Let me confirm the problem: height may be null or have length less than 3, in which case no water can be trapped, return 0; data scale is on the order of 10^5, O(n²) is definitely not feasible; heights are non-negative integers, accumulation may overflow, I'll use long as a safety net. I plan to start from brute force and gradually compress space to O(1)."

This opening conveys boundary awareness and the optimization roadmap in one go, instantly gaining impression points.

After writing the code, don't stop; proactively run test cases:

public static void main(String[] args) {
    Solution s = new Solution();
    System.out.println(s.trap(new int[]{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1})); // 6
    System.out.println(s.trap(new int[]{4, 2, 0, 3, 2, 5}));                    // 9
    System.out.println(s.trap(new int[]{1, 2, 3}));                             // 0
}

"I'll run test cases: [0,1,0,2,1,0,1,3,2,1,2,1] yields 6, [4,2,0,3,2,5] yields 9, empty array and monotonic arrays return 0. Two pointers are O(n) time and O(1) space, already the optimal lower bound. If you're interested, I can also discuss the heap solution for 2D trapping rain water."

The closing script can be memorized directly:

"I would start with brute force, point out that the bottleneck is repeatedly scanning left and right maximums; then use DP preprocessing to reduce time to O(n), but at the cost of space; finally use two pointers plus the barrel effect to optimize space to O(1). In one sentence: the essence of trapping rain water is that the short board determines the water level, and two pointers let us compute locally correct results without knowing global information."

If you get nervous, the 60-second recitation version saves you:

  1. Water per cell = min(leftMax, rightMax) - h[i], barrel effect;
  2. Two preprocess passes achieve O(n) time, O(n) space;
  3. Two pointers compress space to O(1): the shorter side's water level is determined immediately, settle and advance;
  4. Use long to prevent overflow, return 0 if n < 3;
  5. Alternative monotonic stack (row-based, streaming-friendly), advanced can discuss LC 407 min-heap peeling onion.

Finally a memory mnemonic:

By column, look at the max on both sides; by row, rely on monotonic stack; to save space, two pointers; whoever is shorter settles first.

In Conclusion

One sentence to wrap up: Trapping rain water = one barrel effect formula + one optimization chain of "brute force -> DP -> two pointers" + one monotonic stack row-based settlement bonus.

Three actionable suggestions:

  1. Close the article and write the two-pointer version from memory, then explain to someone why "moving the shorter side is correct"; if you can say it, you truly understand it;
  2. Prepare the follow-up question list in advance, especially the LC 11 comparison and LC 407 idea, so you won't panic when asked;
  3. Practice with engineering awareness: boundary guards and overflow protection are the most visible difference between you and memorization-only candidates.

If this article helped you, like, bookmark, and share it, and follow me for more dissections of high-frequency algorithm problems from big companies.

Finally an interaction question: If you meet "Trapping Rain Water" in an interview and the interviewer gives you only 5 minutes, which solution would you write? Have you ever been stuck on the "why move the shorter side" question? Discuss in the comments; I will reply to each one.