DSA Visualizer · 25 visualizationsTrapping Rain Water
Arrays & Hashing
Two SumValid AnagramContains DuplicateGroup AnagramsTop K Frequent ElementsProduct of Array Except SelfLongest Consecutive SequenceStack
Valid ParenthesesBinary Search
Binary SearchTrees & BFS
Binary Tree Level OrderGraphs
Number of IslandsTrees
Invert Binary TreeHardTwo Pointers
Trapping Rain Water
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
The step-through player is coming for this one. Two Sum has the full animation today; the rest are being authored in the admin.
Pythontime O(n) · space O(1)
def trap(height: list[int]) -> int:
l, r = 0, len(height) - 1
maxL, maxR = height[l], height[r]
water = 0
while l < r:
if maxL <= maxR:
l += 1
maxL = max(maxL, height[l])
water += maxL - height[l]
else:
r -= 1
maxR = max(maxR, height[r])
water += maxR - height[r]
return waterTwo Sum is free. Enroll to unlock every visualization and save where you stopped.Enroll free
Watch the video walkthrough