Workspace Largest Rectangle In Histogram
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Largest Rectangle in Histogram visualizer

Learn Largest Rectangle in Histogram 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 / 7Execution step
Reference example · JavaScript
Inspect reference input
[
  2,
  1,
  5,
  6,
  2,
  3
]

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = (a,s)=>{
let st=[],b=0;
for(let i=0;
i<=a.length;
i++){
while(st.length&&(i===a.length||a[st.at(-1)]>a[i])){
let j=st.pop(),w=i-(st.at(-1)??-1)-1;
b=Math.max(b,w*a[j]);
s("Close rectangle at smaller bar",{
Heights:a,Stack:st,Width:[w],Best:[b]
},[j])
}
if(i<a.length)st.push(i)
}
return b
};

Execution canvas

Active Changed
STEP 1

Close rectangle at smaller bar

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

Heights6 items
Stack0 items

Empty at this step.

Width1 items
Best1 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

[
  2,
  1,
  5,
  6,
  2,
  3
]

Execution steps

  1. Close rectangle at smaller bar

Computed output

10
JavaScript reference implementation
const solve = (a,s)=>{
  let st=[],b=0;
  for(let i=0;
  i<=a.length;
  i++){
    while(st.length&&(i===a.length||a[st.at(-1)]>a[i])){
      let j=st.pop(),w=i-(st.at(-1)??-1)-1;
      b=Math.max(b,w*a[j]);
      s("Close rectangle at smaller bar",{
        Heights:a,Stack:st,Width:[w],Best:[b]
      },[j])
    }
    if(i<a.length)st.push(i)
  }
  return b
};

Continue learning

Practice related DSA questions in the same topic.