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 STUDIOLEARN BY DOING Predict. Execute. Understand. Follow the source code, inspect live state changes, and predict the next operation before revealing it.
1 / 6 Execution step
Prediction modePanel width Reference example · JavaScript
Inspect reference input {
"a": [
4,
5,
2,
10,
8
],
"circ": false,
"small": true
} Code Visuals
JavaScript reference implementation · highlighted trace statement
1 const solve = ({
2 a,circ,small
3 },s)=>{
4 let o=Array(a.length).fill(-1 ),st=[];
5 if (small){
6 for (let i=0 ;
7 i<a.length;
8 i++){
9 while (st.length&&a[st.at(-1 )]>=a[i])st.pop();
10 o[i]=st.length?a[st.at(-1 )]:-1 ;
11 st.push(i);
12 s("Discard larger predecessors",{
13 Array:a,Stack:st,Output:o
14 },[i])
15 }
16 }else {
17 for (let i=0 ;
18 i<2 *a.length;
19 i++){
20 let j=i%a.length;
21 while (st.length&&a[st.at(-1 )]<a[j])o[st.pop()]=a[j];
22 if (i<a.length)st.push(j);
23 s("Resolve smaller pending indices",{
24 Array:a,Stack:st,Output:o
25 },[j])
26 }
27 }
28 return o
29 };
Execution canvas Active ChangedSTEP 1 Discard larger predecessors Inspect the highlighted code and the state below. Click individual cells or nodes to see their values.
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 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.