Workspace Online Stock Span
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Online Stock Span visualizer

Learn Online Stock Span 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 / 8Execution step
Reference example · JavaScript
Inspect reference input
[
  100,
  80,
  60,
  70,
  60,
  75,
  85
]

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = (a,s)=>{
let st=[],o=[];
for(let i=0;
i<a.length;
i++){
while(st.length&&a[st.at(-1)]<=a[i])st.pop();
o.push(i-(st.at(-1)??-1));
st.push(i);
s("Find previous greater price",{
Prices:a,Stack:st,Span:o
},[i])
}
return o
};

Execution canvas

Active Changed
STEP 1

Find previous greater price

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

Prices7 items
Stack1 items
Span1 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

[
  100,
  80,
  60,
  70,
  60,
  75,
  85
]

Execution steps

  1. Find previous greater price

Computed output

[
  1,
  1,
  1,
  2,
  1,
  4,
  6
]
JavaScript reference implementation
const solve = (a,s)=>{
  let st=[],o=[];
  for(let i=0;
  i<a.length;
  i++){
    while(st.length&&a[st.at(-1)]<=a[i])st.pop();
    o.push(i-(st.at(-1)??-1));
    st.push(i);
    s("Find previous greater price",{
      Prices:a,Stack:st,Span:o
    },[i])
  }
  return o
};

Continue learning

Practice related DSA questions in the same topic.