Workspace Previous Smaller Element
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Previous Smaller Element visualizer

Learn Previous Smaller Element 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 / 6Execution step
Reference example · JavaScript
Inspect reference input
{
  "a": [
    4,
    5,
    2,
    10,
    8
  ],
  "circ": false,
  "small": true
}

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = ({
a,circ,small
},s)=>{
let o=Array(a.length).fill(-1),st=[];
if(small){
for(let i=0;
i<a.length;
i++){
while(st.length&&a[st.at(-1)]>=a[i])st.pop();
o[i]=st.length?a[st.at(-1)]:-1;
st.push(i);
s("Discard larger predecessors",{
Array:a,Stack:st,Output:o
},[i])
}
}else{
for(let i=0;
i<2*a.length;
i++){
let j=i%a.length;
while(st.length&&a[st.at(-1)]<a[j])o[st.pop()]=a[j];
if(i<a.length)st.push(j);
s("Resolve smaller pending indices",{
Array:a,Stack:st,Output:o
},[j])
}
}
return o
};

Execution canvas

Active Changed
STEP 1

Discard larger predecessors

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

Array5 items
Stack1 items
Output5 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

{
  "a": [
    4,
    5,
    2,
    10,
    8
  ],
  "circ": false,
  "small": true
}

Execution steps

  1. Discard larger predecessors

Computed output

[
  -1,
  4,
  -1,
  2,
  2
]
JavaScript reference implementation
const solve = ({
  a,circ,small
},s)=>{
  let o=Array(a.length).fill(-1),st=[];
  if(small){
    for(let i=0;
    i<a.length;
    i++){
      while(st.length&&a[st.at(-1)]>=a[i])st.pop();
      o[i]=st.length?a[st.at(-1)]:-1;
      st.push(i);
      s("Discard larger predecessors",{
        Array:a,Stack:st,Output:o
      },[i])
    }
  }else{
    for(let i=0;
    i<2*a.length;
    i++){
      let j=i%a.length;
      while(st.length&&a[st.at(-1)]<a[j])o[st.pop()]=a[j];
      if(i<a.length)st.push(j);
      s("Resolve smaller pending indices",{
        Array:a,Stack:st,Output:o
      },[j])
    }
  }
  return o
};

Continue learning

Practice related DSA questions in the same topic.