Skip to content

How to Fix Trapping Rain Water Errors

DodaTech Updated 2026-06-26 1 min read

In this tutorial, you'll learn about How to Fix Trapping Rain Water Errors. We cover key concepts, practical examples, and best practices.

Fix trapping rain water errors when left/right max tracking incorrect or calculation uses min wrong.

Quick Fix

Wrong

def trap(h):
    n=len(h); l_max=[0]*n; r_max=[0]*n
    for i in range(1,n): l_max[i]=max(l_max[i-1],h[i-1])
    for i in range(n-2,-1,-1): r_max[i]=max(r_max[i+1],h[i+1])
    return sum(max(0,min(l_max[i],r_max[i])-h[i]) for i in range(n))

Correct but O(n) space. Two-pointer gives O(1) space.

def trap(h):
    l=0; r=len(h)-1; lm=0; rm=0; ans=0
    while l<r:
        if h[l]<h[r]:
            if h[l]>=lm: lm=h[l]
            else: ans+=lm-h[l]
            l+=1
        else:
            if h[r]>=rm: rm=h[r]
            else: ans+=rm-h[r]
            r-=1
    return ans
[0,1,0,2,1,0,1,3,2,1,2,1] -> 6. O(n) time, O(1) space.

Prevention

Two-pointer from both ends. Track max seen from left and right. Water = min(l_max, r_max) - height.

DodaTech Tools

Doda Browser's algorithm visualizer steps through DSA operations line by line. DodaZIP archives implementation patterns for team sharing. Durga Antivirus Pro detects memory corruption patterns in algorithm implementations.

FAQ

What is trapping rain?

Water trapped between bars. Each position holds min(l_max,r_max)-height.

Two-pointer?

Process shorter side. If current >= max, update max. Else add water.

Why O(1) space?

No arrays. Track left_max and right_max with single variables.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro