Workspace Trapping Rain Water
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Trapping Rain Water visualizer

Learn Trapping Rain Water with a step-by-step Stacks & Queues visualizer, JavaScript source code and a worked example. Practice monotonic structures.

INTERACTIVE EXECUTION STUDIO
LEARN BY DOING

Predict. Execute. Understand.

Follow the source code, inspect live state changes, and predict the next operation before revealing it.

1 / 13Execution step
Reference example · JavaScript
Inspect reference input
[
  0,
  1,
  0,
  2,
  1,
  0,
  1,
  3,
  2,
  1,
  2,
  1
]

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = (a,s)=>{
let l=0,r=a.length-1,lm=0,rm=0,w=0;
while(l<=r){
if(a[l]<=a[r]){
lm=Math.max(lm,a[l]);
w+=lm-a[l++]
}else{
rm=Math.max(rm,a[r]);
w+=rm-a[r--]
}
s("Process lower boundary",{
Heights:a,Bounds:[l,r],Maxima:[lm,rm],Water:[w]
})
}
return w
};

Execution canvas

Active Changed
STEP 1

Process lower boundary

Inspect the highlighted code and the state below. Click individual cells or nodes to see their values.

Heights12 items
Bounds2 items
Maxima2 items
Water1 items
Keyboard: Space to play · Left / Right to stepExplore next problem

Worked example and algorithm walkthrough

Topic: Stacks & Queues · Monotonic structures

Follow the computed execution on the reference input. Advance one step at a time, inspect the changing values and compare your prediction with the final output.

Example input

[
  0,
  1,
  0,
  2,
  1,
  0,
  1,
  3,
  2,
  1,
  2,
  1
]

Execution steps

  1. Process lower boundary

Computed output

6
JavaScript reference implementation
const solve = (a,s)=>{
  let l=0,r=a.length-1,lm=0,rm=0,w=0;
  while(l<=r){
    if(a[l]<=a[r]){
      lm=Math.max(lm,a[l]);
      w+=lm-a[l++]
    }else{
      rm=Math.max(rm,a[r]);
      w+=rm-a[r--]
    }
    s("Process lower boundary",{
      Heights:a,Bounds:[l,r],Maxima:[lm,rm],Water:[w]
    })
  }
  return w
};

Continue learning

Practice related DSA questions in the same topic.