0
0
DSA Pythonprogramming~3 mins

Why Trapping Rain Water Problem in DSA Python?

Choose your learning style9 modes available
The Big Idea

What if you could instantly know how much rainwater your garden holds without measuring every puddle?

The Scenario

Imagine you have a row of uneven walls after a rainstorm, and you want to know how much water is trapped between them. Trying to measure the water manually by looking at each gap is like guessing how much water each dip holds without a clear method.

The Problem

Manually calculating trapped water by checking each gap is slow and confusing. You might miss some trapped water or count it twice. It's easy to make mistakes because you have to consider walls on both sides for every position.

The Solution

The Trapping Rain Water Problem uses a smart way to look at the walls from left and right sides, keeping track of the highest walls seen so far. This helps quickly find how much water each gap can hold without guessing or rechecking.

Before vs After
Before
heights = [3, 0, 2, 0, 4]
water = 0
for i in range(1, len(heights)-1):
    left_max = max(heights[:i])
    right_max = max(heights[i+1:])
    water += max(min(left_max, right_max) - heights[i], 0)
After
left_max = [0]*len(heights)
right_max = [0]*len(heights)
for i in range(1, len(heights)):
    left_max[i] = max(left_max[i-1], heights[i-1])
for i in range(len(heights)-2, -1, -1):
    right_max[i] = max(right_max[i+1], heights[i+1])
water = 0
for i in range(len(heights)):
    water += max(min(left_max[i], right_max[i]) - heights[i], 0)
What It Enables

This concept lets you quickly and accurately find how much water is trapped in any uneven surface, helping in problems like flood simulation and landscape design.

Real Life Example

City planners use this idea to understand how water collects in streets and parks after rain, helping them design better drainage systems to prevent flooding.

Key Takeaways

Manual checking is slow and error-prone.

Using left and right max arrays simplifies the problem.

Enables fast and accurate calculation of trapped water.