Online Stock Span
Master this topic with zero to advance depth.
Online Stock Span
Calculate the 'span' of a stock's price today: the number of consecutive days (including today) the price was less than or equal to today's price.
Visual Representation
Prices: [100, 80, 60, 70, 60, 75, 85]
1. 100: Push (100, 1). Stack: [(100, 1)]
2. 80: Push (80, 1). Stack: [(100, 1), (80, 1)]
3. 70: Pop 60(1). Push (70, 2). Stack: [(100, 1), (80, 1), (70, 2)]
4. 75: Pop 60(1), 70(2). Push (75, 4). Stack: [(100, 1), (80, 1), (75, 4)]Examples
Level I: Brute Force (Linear Lookback per Query)
Intuition
For each new price, scan backwards through all previous prices and count consecutive days where price <= today's price. Stop as soon as a higher price is found.
Level III: Optimal (Monotonic Decreasing Stack)
Intuition
Use a stack to store pairs of (price, span). When a new price is added, pop all elements with price less than or equal to the current one, adding their spans to the current span before pushing it onto the stack.
Detailed Dry Run
| price | Action | Stack Status | Span Output |
|---|---|---|---|
| 100 | Push | [(100, 1)] | 1 |
| 80 | Push | [(100, 1), (80, 1)] | 1 |
| 70 | Pop 60(1) | [(100, 1), (80, 1), (70, 2)] | 2 |
| 85 | Pop 75, 80 | [(100, 1), (85, 6)] | 6 |
⚠️ Common Pitfalls & Tips
Be sure to store the accumulated span span += stack.pop()[1] so that the current element captures all smaller previous spans in constant time.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.