Trapping Rain Water solution explained

In Trapping Rain Water, the water above any bar equals the shorter of the tallest bar to its left and the tallest bar to its right, minus the bar's own height. Computing those two maxima for every bar gives O(n) time with O(n) memory, and two pointers that always advance from the side with the lower wall get the same answer in O(n) time and O(1) extra memory.

By Published 10 min read

The problem in plain terms

Picture a row of upright blocks of different heights, packed together with no gaps, each one unit wide. Rain falls on all of them. Water that lands in a dip between two higher blocks stays there; water at either open end runs off. Given the heights as a list of non-negative integers, return the total number of unit squares of water left standing.

Profiles made up for this page, with answers checked by running the code
HeightsWaterWhat happens
[3, 0, 2, 0, 4]73 + 1 + 3 above the three inner bars, capped by the 3 on the left
[4, 1, 3]2One dip, held at height 3 by the right wall
[5, 0, 0, 0, 5]15A flat pool three wide and five deep
[1, 2, 3, 4]0Rising steadily, so everything drains left
[6, 1, 4, 0, 2, 5]13The right wall of 5 sets the level for every inner bar
Profiles made up for this page, with answers checked by running the code. Scroll sideways on a small screen.

Before you start, confirm three things: heights are whole numbers and never negative, an empty list or a list shorter than three bars holds nothing, and the answer is a single total rather than the water per bar. Interviewers sometimes ask for the per-bar list as a second step, and the methods below produce it with a one-line change.

Why interviewers like it

This is one of the few problems where the brute force, the memory-heavy linear answer and the constant-memory answer are all short, so a single interview slot can test whether you improve a solution step by step. It also checks something harder to fake: whether you can explain why the two-pointer version is correct. Many people remember that it uses pointers and then cannot say why moving the lower side is safe. If you can, you have shown the reasoning the round is designed to find.

The one fact everything rests on

Look at a single bar at index i. Water above it can rise until it would spill over the lower of the two walls that surround it, and the walls that matter are the tallest bar anywhere to the left and the tallest bar anywhere to the right. So the level above bar i is min(maxLeft, maxRight), and the water there is that level minus the bar's own height. If the bar itself is the tallest on one side, the formula gives zero, which is right: nothing sits on a peak.

The formula applied to [3, 0, 2, 0, 4]
IndexHeightTallest on the leftTallest on the rightWater
03340
10343
22341
30343
44440
The formula applied to [3, 0, 2, 0, 4]. Scroll sideways on a small screen.

Here the tallest-on-the-left and tallest-on-the-right values include the bar itself, which keeps every term at zero or above without a separate check.

Brute force: look both ways from every bar

Apply the formula directly. For each bar, scan the whole left side and the whole right side for their maxima. Each scan is O(n), so the total is O(n²) time and O(1) extra space. Say this version out loud first; it proves you have the formula, and the repeated scans are the obvious waste to remove next.

def water_brute(heights):
    total = 0
    for i, h in enumerate(heights):
        tallest_left = max(heights[: i + 1])
        tallest_right = max(heights[i:])
        total += min(tallest_left, tallest_right) - h
    return total
Direct per-bar formula, O(n²). Slicing makes copies, which is fine for a reference.

Linear time: precompute both running maxima

The brute force recomputes the same maxima again and again. Compute them once instead: one pass from the left fills left_max[i], one pass from the right fills right_max[i], and a third pass applies the formula. Three passes is still O(n), and the two helper lists cost O(n) memory. Many interviewers accept this as a complete answer and then ask whether you can drop the extra lists.

def water_prefix(heights):
    n = len(heights)
    if n == 0:
        return 0
    left_max = [0] * n
    right_max = [0] * n
    left_max[0] = heights[0]
    for i in range(1, n):
        left_max[i] = max(left_max[i - 1], heights[i])
    right_max[n - 1] = heights[n - 1]
    for i in range(n - 2, -1, -1):
        right_max[i] = max(right_max[i + 1], heights[i])
    return sum(min(left_max[i], right_max[i]) - heights[i] for i in range(n))
Running maxima from each side, O(n) time and O(n) space.

Constant memory: two pointers that move the lower side

Keep a pointer at each end and the tallest bar seen so far from each side. At every step, compare the two bars under the pointers and process the shorter one. Suppose the left bar is lower than the right bar. The water above the left bar is limited by min(maxLeft, maxRight). We know maxLeft exactly, since we have walked every bar to its left. We do not know maxRight exactly, but we know it is at least the current right bar, which is already taller than the left bar. Any extra height on the right can only raise maxRight further, and the minimum is already decided by the left side. So the water at the left pointer is simply maxLeft minus its height, and we can move on. The same argument, mirrored, handles the right pointer.

def water(heights):
    left, right = 0, len(heights) - 1
    best_left = best_right = 0
    total = 0
    while left < right:
        if heights[left] < heights[right]:
            best_left = max(best_left, heights[left])
            total += best_left - heights[left]
            left += 1
        else:
            best_right = max(best_right, heights[right])
            total += best_right - heights[right]
            right -= 1
    return total
Python: two pointers, O(n) time and O(1) extra space.
function trappedWater(heights) {
  let left = 0;
  let right = heights.length - 1;
  let bestLeft = 0;
  let bestRight = 0;
  let total = 0;
  while (left < right) {
    if (heights[left] < heights[right]) {
      bestLeft = Math.max(bestLeft, heights[left]);
      total += bestLeft - heights[left];
      left += 1;
    } else {
      bestRight = Math.max(bestRight, heights[right]);
      total += bestRight - heights[right];
      right -= 1;
    }
  }
  return total;
}
JavaScript: the same loop.

Trace it on [6, 1, 4, 0, 2, 5]. The left bar of 6 is taller than the right bar of 5, so the right pointer moves on every step. Moving inward it adds 0 for the 5 itself, then 3 above the 2, 5 above the 0, 1 above the 4 and 4 above the 1, for 13 in total. The left side never needed processing, because the 6 guaranteed that the right wall of 5 was always the binding limit. The loop stops when the pointers meet, and the bar where they meet is the tallest one seen, so it holds no water and skipping it is safe.

Another linear answer: a stack of walls

Instead of filling water column by column, you can fill it layer by layer. Keep a stack of indexes whose heights never increase from bottom to top. When a taller bar arrives, pop the top as the floor of a pool; the new top of the stack is the left wall and the current bar is the right wall. The pool adds width times depth, where the width is the gap between the walls and the depth is the lower wall minus the floor. Each index is pushed and popped once, so this is O(n) time with O(n) space in the worst case. It is worth knowing because the same monotonic-stack idea solves next-greater-element and largest-rectangle problems.

def water_stack(heights):
    stack = []  # indexes of bars, heights never increasing from bottom to top
    total = 0
    for i, h in enumerate(heights):
        while stack and heights[stack[-1]] < h:
            floor = heights[stack.pop()]
            if not stack:
                break
            wall = stack[-1]
            width = i - wall - 1
            depth = min(heights[wall], h) - floor
            total += width * depth
        stack.append(i)
    return total
Monotonic stack that fills horizontal layers, O(n) time.

Complexity at a glance

n is the number of bars
ApproachTimeExtra spaceWhen to use it
Per-bar scansO(n²)O(1)Opening answer and test reference
Running maxima listsO(n)O(n)Easiest linear version to get right
Two pointersO(n)O(1)The answer most interviewers aim for
Monotonic stackO(n)O(n)Shows a second pattern; fills by layers
n is the number of bars. Scroll sideways on a small screen.

Edge cases to run

  • Empty list, one bar or two bars: always zero, and the pointer loop never adds anything.
  • All bars the same height: zero, since there is no dip.
  • Strictly rising or strictly falling heights: zero, the water drains off the low end.
  • All zeros: zero. A profile like [5, 0, 0, 0, 5]: a wide flat pool.
  • Two equal tallest bars at the ends with uneven ground between, which exercises the else branch when heights tie.
  • Very large heights in a fixed-width language: the total can exceed a 32-bit int even when each height fits, so accumulate in a 64-bit type.

Mistakes that cost the round

  • Using only the nearest taller neighbor instead of the tallest bar on each side. Water is held by the highest wall, not the closest one.
  • Moving the taller side in the two-pointer loop. That breaks the argument and gives wrong totals on uneven profiles.
  • Updating the running maximum after adding water instead of before, which can produce negative contributions.
  • Counting water above the first or last bar. Nothing can be held at an open edge.
  • Claiming the stack version is O(n²) because of the inner while loop. Each index is popped at most once across the whole run.

How to explain it out loud

Fictional example

Getting from the formula to two pointers in four turns
Candidate
The water on any bar is the lower of the tallest wall on each side, minus the bar. Scanning both sides per bar is n squared, so I would precompute the left and right maxima and get linear time with two extra arrays.
Interviewer
Can you do it without the arrays?
Candidate
Yes. I keep a pointer at each end and process whichever bar is lower. If the left bar is lower, the right side already has something taller, so the left maximum is the binding wall and I can add its water right away.
Candidate
Each step moves one pointer inward, so it is still linear, and I only store two maxima, so the extra memory is constant.

Follow-ups to expect

  • Return the water per bar. Same formula; write each contribution into a list instead of adding it to a total.
  • The heights arrive as a stream. You cannot know the right side yet. The stack version adapts best, since it settles a pool as soon as its right wall shows up.
  • Container with the most water. A related two-pointer problem where you pick only two walls and ignore the bars between them; the move-the-shorter-side logic carries over.
  • A two-dimensional height map. Water can escape in four directions, so the pointer trick no longer works. The usual answer starts from the border and grows inward with a min-heap.

If the pointer argument feels shaky, start with Two Sum on a sorted array, where the same kind of safe-discard reasoning is easier to see. Sliding Window Maximum uses a monotonic structure like the stack above, but keeps it in a deque so old indexes can leave from the front. Valid Palindrome is the gentlest inward-pointer problem of the set. More are grouped by pattern on the coding problems hub.

Rehearsing Trapping Rain Water with Natively

The part of this problem that trips people up is the spoken proof, so record yourself giving it. Natively runs on a Mac or Windows computer and transcribes a mock round as you talk, so afterward you can reread whether the step from two arrays to two pointers was actually justified or just asserted. In practice it can also read the bar diagram from a screenshot and propose an approach to compare with yours once you have committed. The AI assistant for coding interviews describes those features.

Questions people ask

What is the formula for Trapping Rain Water?

For each bar, water equals the smaller of the tallest bar on its left and the tallest bar on its right, minus the bar's own height. Add that over every bar to get the total.

What is the optimal solution to Trapping Rain Water?

Two pointers from both ends, always processing the lower side while tracking the tallest bar seen from each side. It runs in O(n) time with O(1) extra space.

Why is it safe to move the pointer on the lower side?

If the left bar is lower than the right bar, the right side already has a wall at least that tall, so the left running maximum alone decides the water at the left pointer. The mirrored argument covers the right side.

Can Trapping Rain Water be solved with a stack?

Yes. Keep a stack of indexes with non-increasing heights; when a taller bar arrives, pop the floor and add width times depth for the pool between the new top and the current bar. It is O(n) time and O(n) space.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP