Tech Interview RoomStudy guides

Two Pointers

Trapping rain water.

Advanced · 2 min read · Lesson 5 of 5 in Two Pointers

Problem

Given bar heights, compute how much water is trapped after rain. [0,1,0,2,1,0,1,3,2,1,2,1] → 6.

Approach

Water above index i = min(maxLeft[i], maxRight[i]) - height[i]. Computing prefix and suffix maxima takes O(n) extra space. The two-pointer version uses O(1): move the pointer on the side with the smaller maximum, because that side's water level is bounded by its own maximum regardless of what lies in between.

java
class TrappingRainWater {
    static int trap(int[] h) {
        int left = 0, right = h.length - 1, leftMax = 0, rightMax = 0, water = 0;
        while (left < right) {
            if (h[left] < h[right]) {
                leftMax = Math.max(leftMax, h[left]);
                water += leftMax - h[left];      // bounded by leftMax, since a taller bar exists on the right
                left++;
            } else {
                rightMax = Math.max(rightMax, h[right]);
                water += rightMax - h[right];
                right--;
            }
        }
        return water;
    }

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

Complexity

O(n) time, O(1) space.

Follow-up questions interviewers ask

Try answering each one before you open it.

Explain the monotonic stack solution.

Scan left to right keeping a stack of indices with decreasing heights. When a bar taller than the stack top arrives, pop the top (the "bottom" of a basin); the new top is the left wall and the current bar is the right wall; add (min(left wall, right wall) - bottom) × width. Each index is pushed and popped once, so it is O(n) time and O(n) space. Monotonic stacks also solve "next greater element" and "largest rectangle in histogram".