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.
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
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
};