Trapping Rain Water
Calculate water trapped between elevation bars Input: array of non-negative integers representing heights Output: total water units trapped
Given non-negative integer heights of bars of width 1, determine the water retained after rain, with water escaping beyond either end. Part 1 returns the total integer volume, while Part 2 returns an array containing the water above each bar. The water above a bar cannot rise above the lower of the tallest barriers on its two sides. Part 3 takes a rectangular matrix of non-negative integer heights for unit-square cells and returns the total volume retained when water can flow between horizontally or vertically adjacent cells and escape through the outer boundary. Empty inputs retain no water, and Part 2 returns an empty array for an empty input.
Examples
You write
trap_water(height: List[int])
Example 1
- Input
- height = [0,1,0,2,1,0,1,3,2,1,2,1]
- returns
- 6
Example 2
- Input
- height = [4,2,0,3,2,5]
- returns
- 9
The pattern behind it
Arrays & Hashing
I reach for it when
- You catch yourself scanning the array again for every element.
- The problem asks about duplicates, pairs, counts or groups.
Say this before you type. Say what the key is and what the value remembers, before you write the loop.
All 127 Arrays & Hashing problemsStack
I reach for it when
- Things must close in the reverse order they opened.
- You need the nearest earlier or later item that is bigger or smaller.
Say this before you type. Say what each item on the stack is waiting for, and what lets you pop it.
All 17 Stack problems
Meet Coco
Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.
Each locked part opens in the editor once the part before it passes.
Prep guides that list this problem
Our company tags come from public interview write-ups. None of these is a confirmed question.