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
- The span of day i is how many consecutive days up to and including today had a price ≤ today’s.
- Keep a stack of days with higher prices.
- Pop every day whose price is ≤ today: they are all inside today’s span.
- 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…