Trapping Rain Water — Why This Simple Problem Is Fascinating for System Designers
tl;dr: A systems-design perspective on Trapping Rain Water: from brute force to streaming-style state minimization.
At first glance, Trapping Rain Water looks like a typical coding interview problem. Given an array representing elevation heights, compute how much water is trapped after rain.
Most people see it as an algorithm puzzle.
From a system design mindset, it is surprisingly beautiful.
The Naive Way: Local Thinking
The first instinct is simple:
For every position:
- Find the tallest bar on the left
- Find the tallest bar on the right
- Water stored =
min(left_max, right_max) - height[i]
This works, but it requires scanning the array repeatedly.
Time complexity: O(n²).
This is how many systems start in real life: locally correct, globally inefficient.
First Optimization: Precomputation
We realize something important:
The left max and right max values are reused many times.
So we precompute them.
left_max[i]right_max[i]
Now each index becomes a constant-time lookup.
Time complexity becomes O(n), but we pay with extra memory.
This resembles many backend systems:
- Pre-aggregations
- Materialized views
- Cached metadata
We trade space for speed.
The Elegant Solution: Two Pointers
Then comes the real architectural insight.
We notice something subtle:
Water at a position depends on the smaller boundary.
So we do not need full arrays.
We maintain:
left_maxright_max- Two pointers moving inward
Whichever side has the smaller max determines the water.
Now we achieve:
- O(n) time
- O(1) space
This is the same evolution seen in scalable systems:
| Stage | System Analogy |
|---|---|
| Brute force | Repeated database queries |
| Precompute | Caching / indexing |
| Two pointers | Streaming computation |
The Deeper System Design Lesson
The problem teaches a fundamental architecture principle:
Global constraints can often be solved using minimal local state.
Instead of storing everything, we track only what matters:
- Current left boundary
- Current right boundary
This mirrors:
- Streaming pipelines
- Distributed log processing
- Real-time analytics systems
You do not store the whole world. You track just enough state to make the next decision.
Why I Love This Problem
It compresses a deep systems idea into 20 lines of code.
You start with brute force thinking.
Then caching.
Then finally realize:
The system only needs two moving boundaries.
A tiny algorithm that quietly teaches how scalable systems evolve.
And that is why Trapping Rain Water is more than an interview question.
It is a lesson in architecture thinking.