Workspace Maximal Rectangle
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Maximal Rectangle visualizer

Learn Maximal Rectangle 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 / 21Execution step
Reference example · JavaScript
Inspect reference input
[
  [
    1,
    0,
    1,
    0,
    0
  ],
  [
    1,
    0,
    1,
    1,
    1
  ],
  [
    1,
    1,
    1,
    1,
    1
  ],
  [
    1,
    0,
    0,
    1,
    0
  ]
]

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = (a,s)=>{
let h=Array(a[0].length).fill(0),b=0;
for(let row of a){
h=h.map((v,i)=>row[i]?v+1:0);
let st=[];
for(let i=0;
i<=h.length;
i++){
while(st.length&&(i===h.length||h[st.at(-1)]>h[i])){
let j=st.pop();
b=Math.max(b,h[j]*(i-(st.at(-1)??-1)-1));
s("Evaluate histogram rectangle",{
Matrix:a,Heights:h,Stack:st,Best:[b]
})
}
if(i<h.length)st.push(i)
}
}
return b
};

Execution canvas

Active Changed
STEP 1

Evaluate histogram rectangle

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

Matrix4 rows
Heights5 items
Stack0 items

Empty at this step.

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

[
  [
    1,
    0,
    1,
    0,
    0
  ],
  [
    1,
    0,
    1,
    1,
    1
  ],
  [
    1,
    1,
    1,
    1,
    1
  ],
  [
    1,
    0,
    0,
    1,
    0
  ]
]

Execution steps

  1. Evaluate histogram rectangle

Computed output

6
JavaScript reference implementation
const solve = (a,s)=>{
  let h=Array(a[0].length).fill(0),b=0;
  for(let row of a){
    h=h.map((v,i)=>row[i]?v+1:0);
    let st=[];
    for(let i=0;
    i<=h.length;
    i++){
      while(st.length&&(i===h.length||h[st.at(-1)]>h[i])){
        let j=st.pop();
        b=Math.max(b,h[j]*(i-(st.at(-1)??-1)-1));
        s("Evaluate histogram rectangle",{
          Matrix:a,Heights:h,Stack:st,Best:[b]
        })
      }
      if(i<h.length)st.push(i)
    }
  }
  return b
};

Continue learning

Practice related DSA questions in the same topic.