Trapping Rain Water
Problem Statement
You are given n bars standing side by side, each 1 unit wide. height[i] is the height of bar i.
Rain falls on them. Water collects in the dips between taller bars, and anything that isn't held in by a bar on both sides flows away.
Return the total amount of water trapped.
An integer array height of length n.
One integer: the total units of trapped water.
Water per cell is [0, 0, 1, 0, 1, 2, 1, 0, 0, 1, 0, 0], which adds up to 6.
The walls 4 and 5 hold the water. Per cell: [0, 2, 4, 1, 2, 0] = 9.
- • 1 ≤ n ≤ 2 · 10^4
- • 0 ≤ height[i] ≤ 10^5
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
For each cell, scan left for the tallest bar and right for the tallest bar
Precompute the tallest bar up to each index from both sides
Settle the cell on the side whose running max is smaller
For each cell i, scan everything to its left to find the tallest bar, and everything to its right to find the tallest bar (both including i). The water stands at the lower of those two walls, so cell i holds min(leftMax, rightMax) − height[i]. Add it up.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Two Pointers translate into production architectures and low-level memory mechanics.
Circular Buffer & Ring Queue
Two pointer read/write head synchronization in production memory pools.
Pointers vs References Deep Dive
Pointer arithmetic, dereferencing semantics, and memory layout behind in-place array passes.
const Correctness & East-Const
Passing read-only spans with const int* without copying buffers.