Rainwater Trapped Across Unit-Width Elevation Columns

Medium · Coding & Algorithms · Quantitative Researcher · Technical Screen

Problem Statement

You are given a sequence of contiguous vertical columns, each of horizontal width 1, resting side by side on level ground without gaps. Column i rises to integer height heights[i] (0 indicates ground level). Neither the left edge before index 0 nor the right edge after index len(heights) - 1 has a retaining wall, so water that is not enclosed on both sides drains off the ends.

Implement the function:

def trapped_water(heights: list[int]) -> int:

Compute and return the total volume of rainwater retained across the profile, counted in 1 x 1 unit cells:

  • Consider the 1 x 1 cell above column i spanning vertical elevation y to y + 1 (for integer y >= 0).
  • That cell retains water if and only if heights[i] <= y, at least one column L < i satisfies heights[L] > y, and at least one column R > i satisfies heights[R] > y.
  • Every other cell above heights[i] spills away.

Examples

Example 1

Input: heights = [4, 1, 2, 0, 5]
Output: 9

Walk-through: Between the column of height 4 at index 0 and the column of height 5 at index 4, water settles at elevation 4. Columns 1, 2, and 3 retain 4 - 1 = 3, 4 - 2 = 2, and 4 - 0 = 4 unit cells (3 + 2 + 4 = 9).

Example 2

Input: heights = [0, 2, 4, 3, 1]
Output: 0

Walk-through: Heights climb to a single central peak at index 2 and descend afterward, so no column has a strictly taller boundary on both left and right.

Example 3

Input: heights = [2, 0, 3, 1, 0, 2, 4]
Output: 8

Walk-through: Column 1 sits between height 2 (index 0) and height 3 (index 2), trapping 2 cells up to elevation 2. Columns 3, 4, and 5 sit between height 3 (index 2) and height 4 (index 6), filling to elevation 3 and trapping 2, 3, and 1 cells (2 + 2 + 3 + 1 = 8).

Constraints

  • 1 <= len(heights) <= 10^5
  • 0 <= heights[i] <= 10^5
  • The total retained cell count can exceed 2^31 - 1 (up to roughly 10^10); Python's arbitrary-precision int handles this without overflow.

Step-by-step walkthrough

  1. Visualize the profile and find the water at one bar

    Let's draw Example 1 (heights = [4, 1, 2, 0, 5]), using # for solid column blocks and ~ for retained unit cells of water:

    level
      5 |             #
      4 | #  ~  ~  ~  #
      3 | #  ~  ~  ~  #
      2 | #  ~  #  ~  #
      1 | #  #  #  ~  #
        +---------------
      i = 0  1  2  3  4
      h = 4  1  2  0  5
    water 0  3  2  4  0   -> total = 9
    

    Look at any single column i. Water rises above heights[i] until it spills over whichever side has the lower tallest wall:

    • Let L be the tallest bar in heights[0 .. i] (from the left edge through i itself).
    • Let R be the tallest bar in heights[i .. n - 1] (from i itself through the right edge).

    Water at column i settles at level min(L, R). Since the bar itself takes up the bottom heights[i] squares, the number of water squares above column i is:

    water[i] = min(L, R) - heights[i]
    

    Including bar i itself inside L and R is a handy trick: both L and R are automatically at least heights[i], so min(L, R) - heights[i] is 0 when bar i is a peak and never turns negative.

  2. Start from brute force and precomputed arrays

    If we apply min(L, R) - heights[i] directly by scanning left for L and scanning right for R at every column i, each of the n columns scans O(n) bars. That takes O(n^2) time — roughly 10^10 steps when n = 100,000, which is far too slow.

    Why is the brute-force scan wasteful? Adjacent columns compute almost the exact same left maximum! You could fix the speed by precomputing two arrays in O(n) time: one pass left-to-right for left_max[i] and one pass right-to-left for right_max[i].

    Can we keep that O(n) single-pass speed without allocating two O(n) arrays? Yes — notice that min(L, R) only cares about the smaller of the two walls, not the exact height of the taller one.

  3. Key insight: two pointers and the taller anchor wall

    Place one pointer left at index 0 and another pointer right at index n - 1. Maintain two running numbers as the pointers walk inward:

    • left_max: the tallest bar seen so far in heights[0 .. left]
    • right_max: the tallest bar seen so far in heights[right .. n - 1]

    At column left, we already know its full left wall L = left_max. We haven't scanned the middle bars yet, so we don't know the exact tallest bar R to its right — but we don't need R's exact value if we already know R >= left_max! Whenever R >= left_max, min(L, R) simplifies straight to left_max.

    Here is the invariant that gives us that guarantee: at every step, compare heights[left] and heights[right], and only move the shorter pointer inward.

    heights[0 .. left]          unseen middle          heights[right .. n - 1]
      tallest = left_max                                 tallest = right_max
                  |                                        |
                  v                                        v
             heights[left]   <=   heights[right]  (taller anchor stays put!)
    

    Why does heights[left] <= heights[right] guarantee heights[right] >= left_max? Because we never step past the taller of the two current bars! Every bar we stepped past earlier on the left was shorter than (or equal to) whichever right-side bar was standing there at the time, and the current heights[right] is at least as tall as all of them. So heights[right] acts as an unmoved anchor wall that is at least left_max, locking in water[left] = left_max - heights[left].

    By symmetry, when heights[left] > heights[right], heights[left] is an anchor wall at least as tall as right_max, locking in water[right] = right_max - heights[right].

  4. Write the two-pointer loop

    In each iteration of while left < right, check which pointer stands at the shorter (or tied) bar, update that side's running maximum before subtracting the bar's height, add the trapped water, and advance that pointer one step inward.

    def trapped_water(heights: list[int]) -> int:
        # Two pointers starting at the extreme left and right bars of the profile.
        left = 0
        right = len(heights) - 1
    
        # Running maximum bar heights seen so far:
        # - left_max:  max height in heights[0 .. left]
        # - right_max: max height in heights[right .. len(heights) - 1]
        left_max = 0
        right_max = 0
        total_water = 0
    
        # Walk the shorter pointer inward until both pointers meet at a tallest bar.
        while left < right:
            if heights[left] <= heights[right]:
                # Because we never move the taller pointer, heights[right] is at least
                # as tall as every bar we already passed on the left (heights[right] >= left_max).
                # That guarantees the right side has a wall >= left_max, so left_max
                # is the exact water level at `left`.
                if heights[left] > left_max:
                    # Update left_max first so a new tallest bar adds 0, never negative water.
                    left_max = heights[left]
                total_water += left_max - heights[left]
                left += 1
            else:
                # Mirror case: heights[left] > heights[right], and heights[left] >= right_max,
                # so right_max is the exact water level at `right`.
                if heights[right] > right_max:
                    right_max = heights[right]
                total_water += right_max - heights[right]
                right -= 1
    
        return total_water
    

    Why stop at left < right without processing the meeting bar? Because we never move away from a tallest bar, the two pointers always meet at a global maximum bar of the entire array — and a tallest bar never holds water above itself.

  5. Trace the pointers on two examples

    First, trace Example 1 (heights = [4, 1, 2, 0, 5]), where the right wall (5) is tallest:

    left  right  compare   update & water added                left_max  right_max  total_water
      0     4    4 <= 5    left_max = 4; add 4 - 4 = 0; l=1       4          0           0
      1     4    1 <= 5    add 4 - 1 = 3;               l=2       4          0           3
      2     4    2 <= 5    add 4 - 2 = 2;               l=3       4          0           5
      3     4    0 <= 5    add 4 - 0 = 4;               l=4       4          0           9
      4     4    stop (pointers meet at height 5) -> return 9
    

    Now trace [5, 1, 0, 2], where the left wall (5) is taller so right moves instead:

    left  right  compare   update & water added                left_max  right_max  total_water
      0     3    5 > 2     right_max = 2; add 2 - 2 = 0; r=2      0          2           0
      0     2    5 > 0     add 2 - 0 = 2;                r=1      0          2           2
      0     1    5 > 1     add 2 - 1 = 1;                r=0      0          2           3
      0     0    stop (pointers meet at height 5) -> return 3
    

    Both traces match the physical water level without ever needing extra arrays.

  6. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def trapped_water(heights: list[int]) -> int:
        # Two pointers starting at the extreme left and right bars of the profile.
        left = 0
        right = len(heights) - 1
    
        # Running maximum bar heights seen so far:
        # - left_max:  max height in heights[0 .. left]
        # - right_max: max height in heights[right .. len(heights) - 1]
        left_max = 0
        right_max = 0
        total_water = 0
    
        # Walk the shorter pointer inward until both pointers meet at a tallest bar.
        while left < right:
            if heights[left] <= heights[right]:
                # Because we never move the taller pointer, heights[right] is at least
                # as tall as every bar we already passed on the left (heights[right] >= left_max).
                # That guarantees the right side has a wall >= left_max, so left_max
                # is the exact water level at `left`.
                if heights[left] > left_max:
                    # Update left_max first so a new tallest bar adds 0, never negative water.
                    left_max = heights[left]
                total_water += left_max - heights[left]
                left += 1
            else:
                # Mirror case: heights[left] > heights[right], and heights[left] >= right_max,
                # so right_max is the exact water level at `right`.
                if heights[right] > right_max:
                    right_max = heights[right]
                total_water += right_max - heights[right]
                right -= 1
    
        return total_water
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine pouring rain onto a row of stone pillars standing side by side: above any single pillar, water can only rise as high as the shorter of two walls — the tallest pillar anywhere to its left and the tallest pillar anywhere to its right — because any higher water simply spills over the lower side. Using two pointers (a technique where two indices start at opposite ends of an array and walk toward each other), we stand at both outer edges and always step inward from whichever edge currently has the shorter pillar. Because we never move away from the taller pillar, it stays put as an "anchor wall" that is guaranteed to be at least as tall as every pillar we have already walked past on the opposite side, letting us lock in that side's water column immediately.

Why not just scan left and scan right from every single pillar to find its two bounding walls? Doing a full left-and-right scan for each of the n pillars repeats almost identical work n times, costing O(n^2) time — around 10 billion operations when n = 100,000. Precomputing two helper arrays of running maxima from the left and from the right brings the time down to O(n), and the two-pointer trick achieves the exact same O(n) single pass while using O(1) extra memory instead of two n-element arrays.

Let's watch the pointers walk inward on heights = [4, 1, 3, 0, 2]:

Start: left=0 (h=4), right=4 (h=2), left_max=0, right_max=0, total_water=0

1. h[left]=4 > h[right]=2  -> anchor at left (4); right_max=2; add 2-2=0; right -> 3
2. h[left]=4 > h[right]=0  -> anchor at left (4 >= right_max 2); add 2-0=2; right -> 2
3. h[left]=4 > h[right]=3  -> anchor at left (4); right_max=3; add 3-3=0; right -> 1
4. h[left]=4 > h[right]=1  -> anchor at left (4 >= right_max 3); add 3-1=2; right -> 0
5. left == right == 0      -> pointers meet at tallest bar (4); stop with total_water = 4

Column 3 (between height 3 and height 2) trapped 2 units up to level 2, and column 1 (between height 4 and height 3) trapped 2 units up to level 3, totaling 4.

Complexity

Let n be len(heights).

  • Time: O(n). For n >= 1, each iteration of while left < right either increments left by 1 or decrements right by 1, so the loop runs n - 1 times and performs O(1) comparisons and arithmetic per step.
  • Space: O(1). We only store five integer variables (left, right, left_max, right_max, and total_water), regardless of how large heights grows.

Edge cases

  • One or two bars ([5] or [3, 0]): With one bar, left == right == 0 immediately so the loop never runs and returns 0. With two bars, one iteration updates a running maximum and adds max - max = 0.
  • Flat bare ground ([0, 0, 0, 0]) or single-peak ridge ([0, 2, 4, 3, 1]): Every bar we step past equals the running maximum on its side, so every subtraction adds 0.
  • Unequal outer walls ([5, 0, 0, 2]): Water settles at the lower wall (2), adding 2 + 2 = 4 as right walks left toward the anchor bar of height 5.
  • Equal heights and plateaus ([2, 2, 0, 2, 2]): Using <= in heights[left] <= heights[right] breaks ties cleanly on the left; both 2s set left_max = 2 and only the middle 0 adds 2.
  • Descending runoff tail ([4, 1, 0, 1, 4, 3, 2, 1]): As right walks inward up the 1, 2, 3, 4 slope, right_max rises at every step so right_max - heights[right] == 0 — none of the outer slope traps water.
  • 32-bit integer overflow ([10^5, 0, ..., 0, 10^5]): Two walls of height 100,000 surrounding 99,998 zeros hold 9,999,800,000 units, exceeding 2^31 - 1. Python int grows automatically, whereas C++ or Java requires a 64-bit long long / long.

Common mistakes

  • Using max(L, R) instead of min(L, R): Water spills over whichever bounding wall is shorter, never the taller one.
  • Subtracting heights[left] before updating left_max: Whenever heights[left] > left_max, computing left_max - heights[left] first produces a negative number and shrinks the total. Update left_max first (or wrap the difference in max(0, ...)).
  • Advancing the pointer on the taller side: If you move the taller side on [3, 0, 1], left steps past 3 assuming the right side can hold level 3, overcounting water that actually spills over 1.
  • Treating the whole array as one big basin between heights[0] and heights[-1]: Taller interior bars split the profile into independent pools at higher water levels (as in Example 3).

Alternative approaches

  • Prefix and suffix maximum arrays: Build left_max[i] in one left-to-right pass (left_max[i] = max(left_max[i - 1], heights[i]), meaning each entry stores the maximum of the prefix up to i) and right_max[i] in one right-to-left pass, then sum min(left_max[i], right_max[i]) - heights[i]. This takes O(n) time and O(n) space, and is the easiest version to write under time pressure if you forget the two-pointer invariant.
  • Monotonic stack (layer-by-layer): Maintain a monotonic stack (a stack of indices whose bar heights stay non-increasing from bottom to top). Whenever a new bar is taller than the index on top of the stack, pop that valley floor; if the stack still has a left wall beneath it, add the horizontal strip (min(new_height, left_wall_height) - floor_height) * horizontal_width. This also runs in O(n) time and O(n) space and processes bars strictly left-to-right.

Follow-up questions

  • How would you generalize this problem to a 2D R x C elevation grid? In 2D, water can leak out along crooked winding paths in any of four directions, so two pointers are not enough. Instead, push all border cells into a min-heap (a priority queue that always pops the smallest boundary height in O(log(R * C)) time) to represent the outer "sea wall", then repeatedly pop the lowest boundary cell h, flood any unvisited neighbor nb with max(0, h - height[nb]) water, and push nb into the heap with effective wall height max(h, height[nb]) in O(R * C * log(R * C)) total time.
  • How could you report the trapped water per column or identify each distinct pool? Create an array water = [0] * n and assign water[left] = left_max - heights[left] (or water[right] = right_max - heights[right]) inside the two-pointer loop. To list separate pools, scan water from left to right and group maximal contiguous runs of indices where water[i] > 0.
  • What approach works if column heights arrive one by one in a left-to-right stream and you must update the total after each arrival? Two pointers cannot start before seeing the right end of the stream, so use a monotonic non-increasing stack instead: each newly arrived bar pops any shorter bars to its left and immediately adds the horizontal water strips bounded between the new bar and the next taller bar still on the stack. Every bar is pushed once and popped at most once, giving amortized O(1) time per arrival (meaning even though a tall bar may pop many bars at once, the average work per bar across n arrivals is constant).

Follow-up questions

Similar questions

More Goldman Sachs interview questions

All 35 Goldman Sachs questions →