Skip to content
StackDecode
Stacks & queuesAnimated

Stock Span Problem

Count consecutive earlier days with price ≤ today using a stack.

Time

O(n)

Extra space

O(n)

Use it for

Spans of price runs.

How it works

  1. The span of day i is how many consecutive days up to and including today had a price ≤ today’s.
  2. Keep a stack of days with higher prices.
  3. Pop every day whose price is ≤ today: they are all inside today’s span.
  4. The span is today minus the day now on top of the stack (or all days so far if the stack is empty).

Watch it run

Loading animation…