Rainwater Collected Across Column Heights

Hard · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

You are given an integer list heights describing a row of adjacent vertical blocks, each spanning 1 unit horizontally and standing heights[i] units tall at position i.

During a downpour, water accumulates in valleys bounded by taller blocks on both sides, while any water reaching past index 0 or index len(heights) - 1 drains off the edges. Above position i, standing water reaches up to the smaller of the tallest block on its left (0..i) and the tallest block on its right (i..len(heights) - 1), contributing that surface elevation minus heights[i] units of volume.

Implement trap(heights: List[int]) -> int to return the total volume of standing water retained across the entire profile.

def trap(heights: List[int]) -> int:

Examples

Example 1

  • Input: heights = [3, 1, 0, 2, 1, 4, 1, 3]
  • Output: 10
  • Explanation: Between index 0 (height 3) and index 5 (height 4), the surface stabilizes at height 3, holding 2 + 3 + 1 + 2 = 8 units over indices 1..4. Between index 5 (height 4) and index 7 (height 3), the surface stabilizes at height 3, holding 2 more units at index 6, for 8 + 2 = 10 total.

Example 2

  • Input: heights = [3, 5, 1, 3, 0, 4]
  • Output: 8
  • Explanation: Index 0 sits outside peak 5 with nothing taller further left, so it retains 0. Between index 1 (height 5) and index 5 (height 4), the surface sits at height 4, retaining 3 + 1 + 4 = 8 units across indices 2..4.

Constraints

  • n == len(heights)
  • 0 <= n <= 10^5
  • 0 <= heights[i] <= 10^5
  • Profiles with fewer than 3 blocks, or profiles that only ascend or only descend, retain 0 units.

Step-by-step walkthrough

  1. Visualize how water sits above each column

    Instead of trying to identify entire "ponds" from left to right, look at one single bar i of width 1 and ask: how high does the water surface sit directly above bar i?

    Water above column i is held back on the left by the tallest bar in heights[0..i] and on the right by the tallest bar in heights[i..n-1]. Just like a wooden bucket with one tall slat and one short slat, water spills over whichever side is lower:

    Example 2: heights = [3, 5, 1, 3, 0, 4]   ('#' = block, '~' = retained water)
    
      5 |   #
      4 |   # ~ ~ ~ #   <-- water surface sits at min(5, 4) = 4 across columns 2..4
      3 | # # ~ # ~ #
      2 | # # ~ # ~ #
      1 | # # # # ~ #
        +------------
          3 5 1 3 0 4
      water: 0 + 0 + 3 + 1 + 4 + 0 = 8
    
    Column-by-column formula:
      water_level[i] = min(max(heights[0..i]), max(heights[i..n-1]))
      water[i]       = water_level[i] - heights[i]
    

    Notice a neat trick in that formula: because we include heights[i] itself inside both max(heights[0..i]) and max(heights[i..n-1]), water_level[i] is always at least heights[i], so water[i] can never be negative!

  2. From O(n²) brute force to O(n) prefix and suffix maxima

    Computing max(heights[0..i]) and max(heights[i..n-1]) from scratch for each column i scans up to n elements n times—roughly 10¹⁰ operations when n = 10⁵, which will time out.

    We avoid repeated scanning by noticing that the tallest bar in 0..i is simply max(left_best[i - 1], heights[i]) (a prefix maximum, meaning a running maximum maintained from the start of the array), and similarly for right_best from the right end:

    def trap_with_arrays(heights: List[int]) -> int:
        n = len(heights)
        if n == 0:
            return 0
        left_best = [0] * n
        right_best = [0] * n
        left_best[0] = heights[0]
        for i in range(1, n):
            left_best[i] = max(left_best[i - 1], heights[i])
        right_best[n - 1] = heights[n - 1]
        for i in range(n - 2, -1, -1):
            right_best[i] = max(right_best[i + 1], heights[i])
    
        total_water = 0
        for i in range(n):
            total_water += min(left_best[i], right_best[i]) - heights[i]
        return total_water
    

    This runs in O(n) time, which easily passes time limits, but allocates O(n) extra memory for left_best and right_best. Next, let's eliminate both arrays.

  3. Key idea: settle the shorter side with two pointers in O(1) space

    Place one pointer left = 0 at the far left and one pointer right = n - 1 at the far right, keeping two running integers: - left_max: tallest bar seen so far across heights[0..left] - right_max: tallest bar seen so far across heights[right..n-1]

    At index left, we already know the exact tallest wall on its left (left_max), because left has walked continuously from 0. We do not yet know the exact tallest wall to its right, because heights[left+1 .. right-1] is still unexplored. Why don't we need to know it when heights[left] <= heights[right]?

    Suppose heights[left] <= heights[right], and we update left_max = max(left_max, heights[left]):
    
      Case A: left_max came from heights[left] itself.
              Since heights[left] <= heights[right], bar `right` is already >= left_max!
    
      Case B: left_max came from an earlier bar `j < left` (so left_max == heights[j]).
              How did `left` step past `j` earlier? Only when heights[j] <= heights[r_then]
              for some pointer position `r_then >= right` still sitting to the right of `left`!
    
      [0 ... j ... left]   (unexplored middle)   [right ... r_then ... n-1]
             |                                                |
          left_max  <=  heights[r_then]  <=  true_right_max_of(left)
    

    In both cases, there is definitely a bar to the right of left at least as tall as left_max. Even if an unexplored bar in the middle is 1000 units tall, min(left_max, true_right_max) is still left_max!

    By exact symmetry, whenever heights[left] > heights[right], there is a bar to the left of right taller than right_max, so the water level at right is right_max. Thus at every step we settle the bar under the shorter pointer and step that pointer inward.

  4. Code the two-pointer loop

    Let's translate that rule directly into trap(heights). Notice three clean details: 1. Updating left_max before subtracting heights[left]: if heights[left] sets a new left_max, then left_max - heights[left] is 0, so a new peak adds 0 water without needing max(0, ...). 2. When left == right: the loop stops because the two pointers meet on the tallest bar of the entire array (or a tie for tallest), which can never trap water above itself. 3. Tiny inputs ([], [7], [3, 4]): for [], left = 0 and right = -1, so while left < right skips immediately and returns 0 without ever indexing heights.

    def trap(heights: List[int]) -> int:
        # left, right: inward-moving indices bounding the unsettled slice heights[left..right].
        left = 0
        right = len(heights) - 1
        # left_max, right_max: tallest bar height seen so far from index 0..left and right..n-1.
        left_max = 0
        right_max = 0
        total_water = 0
    
        # When heights has 0 or 1 bars, left >= right initially and the loop safely returns 0.
        while left < right:
            if heights[left] <= heights[right]:
                # Because heights[left] <= heights[right] (and any earlier taller left bar only
                # advanced past an even taller right bar), the true tallest bar to the right of
                # `left` is guaranteed >= left_max, so min(left_wall, right_wall) == left_max.
                if heights[left] > left_max:
                    left_max = heights[left]
                water_at_left = left_max - heights[left]
                total_water += water_at_left
                left += 1
            else:
                # Mirror case: heights[left] > heights[right] guarantees a left wall >= right_max.
                if heights[right] > right_max:
                    right_max = heights[right]
                water_at_right = right_max - heights[right]
                total_water += water_at_right
                right -= 1
    
        return total_water
    
  5. Trace Example 1 and Example 2 step by step

    First, let's trace Example 2 (heights = [3, 5, 1, 3, 0, 4]), where left steps from index 0 up to peak 5 at index 1 and then right walks inward across the basin:

    left  right  heights[L] vs [R]  pointer settled  left_max  right_max  water added  total
    ----  -----  -----------------  ---------------  --------  ---------  -----------  -----
      0     5        3 <= 4         left  (idx 0)       3          0        3 - 3 = 0    0
      1     5        5 > 4          right (idx 5)       3          4        4 - 4 = 0    0
      1     4        5 > 0          right (idx 4)       3          4        4 - 0 = 4    4
      1     3        5 > 3          right (idx 3)       3          4        4 - 3 = 1    5
      1     2        5 > 1          right (idx 2)       3          4        4 - 1 = 3    8
      1     1    loop ends (left == right at tallest bar 5)                returns 8
    

    Now let's trace Example 1 (heights = [3, 1, 0, 2, 1, 4, 1, 3]), where peak 4 sits at index 5 between two separate basins:

    left  right  heights[L] vs [R]  pointer settled  left_max  right_max  water added  total
    ----  -----  -----------------  ---------------  --------  ---------  -----------  -----
      0     7        3 <= 3         left  (idx 0)       3          0        3 - 3 = 0    0
      1     7        1 <= 3         left  (idx 1)       3          0        3 - 1 = 2    2
      2     7        0 <= 3         left  (idx 2)       3          0        3 - 0 = 3    5
      3     7        2 <= 3         left  (idx 3)       3          0        3 - 2 = 1    6
      4     7        1 <= 3         left  (idx 4)       3          0        3 - 1 = 2    8
      5     7        4 > 3          right (idx 7)       3          3        3 - 3 = 0    8
      5     6        4 > 1          right (idx 6)       3          3        3 - 1 = 2   10
      5     5    loop ends (left == right at middle peak 4)                returns 10
    

    Notice how indices 1..4 filled to height 3 (left_max) while index 6 also filled to height 3 (right_max), accumulating 10 units in one linear sweep!

  6. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def trap(heights: List[int]) -> int:
        # left, right: inward-moving indices bounding the unsettled slice heights[left..right].
        left = 0
        right = len(heights) - 1
        # left_max, right_max: tallest bar height seen so far from index 0..left and right..n-1.
        left_max = 0
        right_max = 0
        total_water = 0
    
        # When heights has 0 or 1 bars, left >= right initially and the loop safely returns 0.
        while left < right:
            if heights[left] <= heights[right]:
                # Because heights[left] <= heights[right] (and any earlier taller left bar only
                # advanced past an even taller right bar), the true tallest bar to the right of
                # `left` is guaranteed >= left_max, so min(left_wall, right_wall) == left_max.
                if heights[left] > left_max:
                    left_max = heights[left]
                water_at_left = left_max - heights[left]
                total_water += water_at_left
                left += 1
            else:
                # Mirror case: heights[left] > heights[right] guarantees a left wall >= right_max.
                if heights[right] > right_max:
                    right_max = heights[right]
                water_at_right = right_max - heights[right]
                total_water += water_at_right
                right -= 1
    
        return total_water
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture each bar as a slice of canyon rock and focus on one vertical column at a time. Water above column i rises until it spills over whichever surrounding canyon wall is shorter: the tallest bar anywhere to its left, or the tallest bar anywhere to its right (min(tallest_left, tallest_right) - heights[i]).

Why do simpler approaches do extra work? Scanning outward from every single column to find its left and right walls repeats the same work n times, taking O(n²) time (10¹⁰ operations when n = 10⁵). Precomputing two prefix/suffix maximum arrays (running-maximum tables built in one left-to-right pass and one right-to-left pass) drops the runtime to O(n), but still allocates O(n) extra memory.

The two-pointer technique (placing left at index 0 and right at n - 1 and moving them toward each other) gets O(1) extra space because min(left_wall, right_wall) only depends on the smaller wall! Whenever heights[left] <= heights[right], we already know the true left wall left_max at left, and we know some bar on the right is at least as tall as left_max—so min(left_max, right_wall) is guaranteed to equal left_max right now. Let's trace heights = [3, 0, 1, 0, 2]:

heights = [3, 0, 1, 0, 2]
1. left=0 (3), right=4 (2): 3 > 2  -> settle right: right_max=2, water += 2-2 = 0, right=3
2. left=0 (3), right=3 (0): 3 > 0  -> settle right: right_max=2, water += 2-0 = 2, right=2
3. left=0 (3), right=2 (1): 3 > 1  -> settle right: right_max=2, water += 2-1 = 1, right=1
4. left=0 (3), right=1 (0): 3 > 0  -> settle right: right_max=2, water += 2-0 = 2, right=0
5. left == right == 0 (peak 3)     -> stop! Total trapped water = 0 + 2 + 1 + 2 = 5.

Complexity

Let n = len(heights).

  • Time: O(n). Each iteration of while left < right performs a constant number of comparisons and additions and either increments left by 1 or decrements right by 1, so the loop executes at most max(0, n - 1) times.
  • Space: O(1) auxiliary space. Regardless of how large n grows, we store only five integer variables (left, right, left_max, right_max, and total_water).

Edge cases

  • Empty or tiny inputs (n < 3, e.g. [], [5], [3, 4]): Fewer than 3 bars cannot enclose a valley between two walls; [] and [5] skip the loop immediately (0), and 2-bar inputs update the outer maximum and add 0.
  • Strictly increasing or decreasing ramps ([1, 2, 3, 4] or [4, 3, 2, 1]): Every settled bar raises left_max or right_max to match its own height, contributing 0 water.
  • Asymmetric walls ([5, 0, 0, 0, 1]): Water rises to height 1 (the shorter wall), trapping 3 units total rather than 15.
  • Flat plateaus and ties ([3, 3, 0, 0, 3, 3]): Using <= handles equal heights cleanly; either pointer can step inward on a tie without affecting left_max or right_max.
  • 64-bit overflow in fixed-width languages: With n = 10⁵ and outer walls of height 10⁵ around 0s, trapped water reaches 99,998 * 10⁵ ≈ 10¹⁰, which fits effortlessly in Python int but requires a 64-bit integer (long / int64_t) in C++, Java, or Go.

Common mistakes

  • Advancing the taller pointer instead of the shorter one: If heights[left] > heights[right] and you advance left, no bar on the right is guaranteed to reach left_max, so [2, 0, 1] falsely computes 2 - 0 = 2 instead of 1 (or 0 depending on setup).
  • Subtracting heights[left] before updating left_max: When heights[left] is a brand-new peak (heights[left] > left_max), subtracting first produces a negative number unless wrapped in max(0, ...).
  • Initializing left_max = heights[0] before checking if not heights:: Indexing heights[0] crashes with IndexError when heights == []. Starting both maxima at 0 avoids any special-case branch.
  • Taking max(left_wall, right_wall) instead of min: Water spills over the lower wall, never the higher one.

Alternative approaches

  • Prefix and suffix maximum arrays: Precompute left_best[i] = max(heights[0..i]) and right_best[i] = max(heights[i..n-1]) in two O(n) passes and sum min(left_best[i], right_best[i]) - heights[i]. Runs in O(n) time and O(n) space, and is a great stepping-stone to explain first in an interview.
  • Monotonic stack (horizontal layers): Maintain a monotonic stack—a stack of bar indices kept in non-increasing height order. Whenever a new bar heights[i] is taller than the bar at the top of the stack, pop that valley floor bottom and fill the horizontal rectangle bounded by the new top of the stack left_wall and i with (min(heights[left_wall], heights[i]) - heights[bottom]) * (i - left_wall - 1). Runs in O(n) time and O(n) space.

Follow-up questions

  • Suppose each column i had a custom horizontal width widths[i] rather than unit width; how would you adjust the calculation? A column's horizontal span does not change how high water can rise—the surface above column i is still min(tallest_left, tallest_right). The only change is that a water column of depth d over index i now has cross-sectional area d * widths[i] instead of d * 1. Multiply water_at_left by widths[left] and water_at_right by widths[right] inside the same two-pointer loop, keeping O(n) time and O(1) auxiliary space.
  • Why does the O(1)-space inward two-pointer scan still compute exact column depths without knowing the tallest unexplored bar in the middle? The formula min(true_left_max, true_right_max) obeys a loop invariant (a condition guaranteed to hold on every iteration): whenever heights[left] <= heights[right] and we update left_max = max(left_max, heights[left]), true_left_max at left equals left_max, while true_right_max at left is at least left_max. Either left_max equals heights[left] (which is <= heights[right]), or left_max came from an earlier index j < left that left only stepped past when some right-side bar heights[r_then] satisfied heights[j] <= heights[r_then]. Because true_right_max >= left_max, any even taller bar hidden in the unexplored interior can only increase true_right_max further without changing min(left_max, true_right_max) == left_max.
  • How would you generalize this problem to a 2D elevation matrix where water drains across any of the four cardinal neighbors? In 2D, water escapes along whichever 4-connected path to the outer border has the lowest maximum elevation, so independent row and column maxima fail whenever water snakes around corners. Instead, push all border cells into a min-heap (a priority queue that pops the lowest spill elevation in logarithmic time) and flood inward like Dijkstra's algorithm: repeatedly pop the lowest boundary (level, r, c), and for each unvisited neighbor (nr, nc), accumulate max(0, level - grid[nr][nc]) water and push (max(level, grid[nr][nc]), nr, nc) into the heap. On an R × C matrix, every cell enters and leaves the heap once in O(R * C * log(R * C)) time and O(R * C) space.

Follow-up questions

Similar questions

More Hive.Ai interview questions

All 5 Hive.Ai questions →