LeetCode #901 Medium

Online Stock Span

Online Stock Span is LeetCode 901 (Medium). Design a class StockSpanner whose method next(price) receives one daily stock price at a time and returns that day's span: the number of consecutive days, ending today and going backwards, on which the price was less than or equal to today's price.

  • Today always counts, so every span is at least 1.
  • The prices arrive one by one. You cannot see future prices, and you must answer each call before the next one arrives.
  • Up to 10⁴ calls, so walking back day by day on every call can reach about 5 × 10⁷ steps on a rising market.
Constraints
  • 1 <= price <= 10⁵
  • At most 10⁴ calls will be made to next.
stackmonotonic-stackdesign
Open on LeetCode ↗
02

Intuition

Look at a day that was beaten: some later day had a price at least as high. Any future day that reaches back past that later day also covers the beaten day, and any future day that stops earlier never sees it. So a beaten day never needs to be checked on its own again; it can be folded into the day that beat it.

Keep a stack of (price, span) blocks, where span is how many days that block stands for. A new price pops every block whose price is not higher and adds their spans to its own. What remains on the stack has strictly falling prices from bottom to top, and each block remembers how many days it swallowed.

How to spot this pattern

"How far back does the current value dominate?" asked for every element of a stream is a previous-greater-element question. When the input arrives one value at a time, the stack lives inside the class and is updated per call.

03

Approach

Try it first

Before reading on, decide whether a day that was beaten by a later, higher price can ever end a future span. Use the answer to choose what to keep between calls. Aim for O(1) amortised per call.

1

Keep a stack between calls

The constructor creates an empty stack. Each entry is a pair: a price and the number of consecutive days that price block covers. The stack must survive from one next call to the next, so it is a field of the object.

2

Start the span at 1

Inside next(price), set span = 1 for today. Today's own price is always less than or equal to itself, so today is always part of its span.

3

Swallow blocks that are not higher

While the top block's price is less than or equal to price, pop it and add its span to span. Those days all sit right before today with no higher price in between, so they all belong to today's run.

4

Push today as one block

Push (price, span) and return span. The popped days are now stored inside today's block, so a later, higher price can absorb all of them with a single pop.

04

Code in Python, C++ and Java

▶1class StockSpanner:
▶2 def __init__(self):
▶3 self.stack = []
▶4 
▶5 def next(self, price: int) -> int:
▶6 span = 1
▶7 while self.stack and self.stack[-1][0] <= price:
▶8 span += self.stack.pop()[1]
▶9 self.stack.append((price, span))
▶10 return span
prices so farday 1day 2day 3day 4day 5day 6day 7stackspanno prices yet, empty stack
stackempty
The stack lives inside the object, so it keeps its blocks between calls. Each block will be a price plus the number of days it stands for.
prices so far100day 1day 2day 3day 4day 5day 6day 7stackspan1day 1: price 100, span starts at 1
price100
span1
Today always counts, so the span starts at 1. Now compare 100 with the most recent block on the stack.
prices so far100day 1day 2day 3day 4day 5day 6day 7stack1001 dayspan1nothing left to beat → span 1
return1
blocks1
The stack is empty, so every earlier day was at most 100. Today goes on as one block covering 1 day, ready to be swallowed whole by a higher price later.
prices so far100day 180day 2day 3day 4day 5day 6day 7stack1001 dayspan11day 2: price 80, span starts at 1
price80
span1
Today always counts, so the span starts at 1. Now compare 80 with the most recent block on the stack.
prices so far100day 180day 2day 3day 4day 5day 6day 7stack1001 day801 dayspan11100 is higher, stop → span 1
return1
blocks2
The top block 100 is higher than 80, so the run of days stops there. Today goes on as one block covering 1 day, ready to be swallowed whole by a higher price later.
prices so far100day 180day 260day 3day 4day 5day 6day 7stack1001 day801 dayspan111day 3: price 60, span starts at 1
price60
span1
Today always counts, so the span starts at 1. Now compare 60 with the most recent block on the stack.
prices so far100day 180day 260day 3day 4day 5day 6day 7stack1001 day801 day601 dayspan11180 is higher, stop → span 1
return1
blocks3
The top block 80 is higher than 60, so the run of days stops there. Today goes on as one block covering 1 day, ready to be swallowed whole by a higher price later.
prices so far100day 180day 260day 370day 4day 5day 6day 7stack1001 day801 day601 dayspan1111day 4: price 70, span starts at 1
price70
span1
Today always counts, so the span starts at 1. Now compare 70 with the most recent block on the stack.
prices so far100day 180day 260day 370day 4day 5day 6day 7stack1001 day801 day601 dayspan111260 is not above 70 → take its 1 day, span 2
popped60
span2
The block price 60 is below 70. Its 1 day all sit right before today with nothing higher in between, so they join today's span in one move instead of being checked one by one.
prices so far100day 180day 260day 370day 4day 5day 6day 7stack1001 day801 day702 daysspan111280 is higher, stop → span 2
return2
blocks3
The top block 80 is higher than 70, so the run of days stops there. Today goes on as one block covering 2 days, ready to be swallowed whole by a higher price later.
prices so far100day 180day 260day 370day 460day 5day 6day 7stack1001 day801 day702 daysspan11121day 5: price 60, span starts at 1
price60
span1
Today always counts, so the span starts at 1. Now compare 60 with the most recent block on the stack.
prices so far100day 180day 260day 370day 460day 5day 6day 7stack1001 day801 day702 days601 dayspan1112170 is higher, stop → span 1
return1
blocks4
The top block 70 is higher than 60, so the run of days stops there. Today goes on as one block covering 1 day, ready to be swallowed whole by a higher price later.
prices so far100day 180day 260day 370day 460day 575day 6day 7stack1001 day801 day702 days601 dayspan111211day 6: price 75, span starts at 1
price75
span1
Today always counts, so the span starts at 1. Now compare 75 with the most recent block on the stack.
prices so far100day 180day 260day 370day 460day 575day 6day 7stack1001 day801 day702 days601 dayspan11121260 is not above 75 → take its 1 day, span 2
popped60
span2
The block price 60 is below 75. Its 1 day all sit right before today with nothing higher in between, so they join today's span in one move instead of being checked one by one.
prices so far100day 180day 260day 370day 460day 575day 6day 7stack1001 day801 day702 daysspan11121470 is not above 75 → take its 2 days, span 4
popped70
span4
The block price 70 is below 75. Its 2 days all sit right before today with nothing higher in between, so they join today's span in one move instead of being checked one by one.
prices so far100day 180day 260day 370day 460day 575day 6day 7stack1001 day801 day754 daysspan11121480 is higher, stop → span 4
return4
blocks3
The top block 80 is higher than 75, so the run of days stops there. Today goes on as one block covering 4 days, ready to be swallowed whole by a higher price later.
prices so far100day 180day 260day 370day 460day 575day 685day 7stack1001 day801 day754 daysspan1112141day 7: price 85, span starts at 1
price85
span1
Today always counts, so the span starts at 1. Now compare 85 with the most recent block on the stack.
prices so far100day 180day 260day 370day 460day 575day 685day 7stack1001 day801 day754 daysspan111214575 is not above 85 → take its 4 days, span 5
popped75
span5
The block price 75 is below 85. Its 4 days all sit right before today with nothing higher in between, so they join today's span in one move instead of being checked one by one.
prices so far100day 180day 260day 370day 460day 575day 685day 7stack1001 day801 dayspan111214680 is not above 85 → take its 1 day, span 6
popped80
span6
The block price 80 is below 85. Its 1 day all sit right before today with nothing higher in between, so they join today's span in one move instead of being checked one by one.
prices so far100day 180day 260day 370day 460day 575day 685day 7stack1001 day856 daysspan1112146100 is higher, stop → span 6
return6
blocks2
The top block 100 is higher than 85, so the run of days stops there. Today goes on as one block covering 6 days, ready to be swallowed whole by a higher price later.
05

Common pitfalls

Popping only strictly lower prices

✗ Wrong
while self.stack and self.stack[-1][0] < price:
✓ Right
while self.stack and self.stack[-1][0] <= price:

Equal prices are part of the span. For the calls 5, 5, the strict version leaves the first 5 on the stack and answers 1 for the second day, but the correct span is 2.

Adding 1 per pop instead of the block's span

✗ Wrong
self.stack.pop()
span += 1
✓ Right
span += self.stack.pop()[1]

A popped block may stand for many days. For the calls 1, 2, 3, the day with price 3 pops a single block that already covers 2 days, so it must answer 3, not 2.

06

Edge cases

Prices that only fall, like 50, 40, 30, 20

Nothing is ever popped, every span is 1, and the stack grows by one block per call. This is the case where memory reaches its maximum.

07

Complexity

Time
O(1) amortised per call
Space
O(n)
Every price is pushed once and popped at most once over all calls, so n calls do at most 2n stack operations in total, even though a single call can pop many blocks. With n calls on a falling market the stack holds n blocks.
08

Online Stock Span FAQ

Can I store indices instead of spans?

Yes. Count the calls in a field, push (price, index), and after popping answer index − index of the new top, or index + 1 if the stack is empty. It is the same stack; the span is just recovered from positions.

How is this related to finding the previous greater element?

Today's span ends right after the most recent day with a strictly higher price. The block left on top after the pops is exactly that day, so this class answers the previous greater element for a stream. The array version runs in Next Greater Element with the direction reversed.

Why not keep a list of all prices and walk back?

On a rising market, call k walks back k days, so 10⁴ calls cost about 5 × 10⁷ comparisons. The stack touches each day at most twice in total.