DSA Tracker

Hard

Trapping Rain Water

A hard Arrays problem included in Apna College, Love Babbar 450, Striver A2Z. Below: the roles whose interviews prioritise this topic, and how to practise it.

Topic
Arrays
Sheets
3
Core for
25 roles
Platform
LeetCode

The problem

Given an array of non-negative integers representing bar heights, compute how much rainwater can be trapped between the bars after it rains.

Example 1

Input
[0,1,0,2,1,0,1,3,2,1,2,1]
Output
6

Example 2

Input
[4,2,0,3,2,5]
Output
9

Example 3

Input
[2,0,2]
Output
2

Constraints

  • 1 <= n <= 2*10^4
  • 0 <= height[i] <= 10^5

How to think about it

Updated 2026-09-09

The water trapped directly above any single bar is bottlenecked solely by the shorter of the highest walls to its left and right. Whichever boundary wall is currently lower determines the water level unconditionally, meaning you can process bars inward from the shorter boundary without needing to know future higher walls.

Approaches, worst first

  1. Prefix and suffix max tables

    time O(n) · space O(n)

    Precompute two arrays: one storing the highest bar to the left of each index, and one storing the highest bar to the right. A final pass accumulates min(leftMax[i], rightMax[i]) - height[i], trading 2n space for linear time.

  2. Two-pointer boundary sweepWrite this one

    time O(n) · space O(1)

    Place pointers at 0 and n - 1 with running leftMax and rightMax tallies. Always advance the pointer with the smaller max, because the water above that bar is strictly limited by its own side regardless of how tall the opposing side eventually gets.

Where people lose marks · 3
  • Computing negative trapped water when a bar is taller than both its neighbors instead of clamping water to zero.
  • Arrays with fewer than 3 bars cannot trap any water and must return 0 immediately.
  • Accumulating trapped water in a 32-bit signed integer when n is 2 * 10^4 and heights reach 10^5, which can sum up to 2 * 10^9 and approach signed integer overflow limits.

Full solution

Two-pointer boundary sweep: always advance the side whose running max is smaller, since the water above that bar is capped by its own side no matter how tall the other side turns out. Linear time, constant space, one pass.

Python
from typing import List


def trap(height: List[int]) -> int:
    left, right = 0, len(height) - 1
    left_max = right_max = 0
    water = 0
    while left < right:
        if height[left] < height[right]:
            # left wall is the bottleneck: water here can never exceed left_max
            left_max = max(left_max, height[left])
            water += left_max - height[left]
            left += 1
        else:
            right_max = max(right_max, height[right])
            water += right_max - height[right]
            right -= 1
    return water
JavaScript
function trap(height) {
  let left = 0;
  let right = height.length - 1;
  let leftMax = 0;
  let rightMax = 0;
  let water = 0;
  while (left < right) {
    if (height[left] < height[right]) {
      // left wall is the bottleneck: water here can never exceed leftMax
      leftMax = Math.max(leftMax, height[left]);
      water += leftMax - height[left];
      left++;
    } else {
      rightMax = Math.max(rightMax, height[right]);
      water += rightMax - height[right];
      right--;
    }
  }
  return water;
}
Try it in the editor

The theory behind it

Arrays — the ground this problem stands on. All Arrays problems

What Arrays is

An array is a row of fixed boxes laid side by side in computer memory, like numbered lockers in a hallway. Because each box occupies identical space and sits directly next to its neighbors, jumping to locker zero or locker ten thousand takes the exact same tiny fraction of time. Every box holds an item of the same type, addressed by an offset number called an index.

When to reach for it

Reach for an array when items arrive in a known sequence and need immediate retrieval by position number. Problems asking for running totals, prefix accumulations, cyclic rotations, or in-place rearrangements signal array mechanics. Whenever constraints require constant-time random lookups or contiguous cache scans across fixed collections, a flat sequence is the default container.

How the pattern works

Visualize a tape with zero-indexed slots stretching from start to end. Keep track of write and read cursors when modifying contents without allocating helper buffers. For running computations, maintain an invariant such as having processed all elements left of the current index while pending elements wait to the right. When modifying entries in place, consider scanning backwards from the end so unread data is not overwritten.

What each operation costs

OperationTime
look up element by indexO(1)
insert or delete at the startO(n)
search an unsorted collection for a valueO(n)
What usually goes wrong with Arrays
  • Reading past the final index by checking index less than or equal to length instead of strictly less than length, triggering index out of bounds exceptions.
  • Modifying length or removing elements during a forward iteration loop, which causes remaining items to shift left and skip validation on the next neighbor.
  • Assuming dynamic resizing is costless inside nested loops, causing repeated memory reallocation copies when appending unknown quantities of items.

Which roles need this problem

Arrays is a core topic for these 25 roles — if you're targeting one of them, this problem is early in your path, not optional.

Secondary for 3 more roles, including Database Engineer, Bioinformatics Engineer, Networking Engineer.

Track this in your role's order

Pick your target role and all 370 problems — including this one — resequence to what that interview actually asks. Free.

Start free

More Arrays problems

Problem set and role mapping as of .