The Online Stock Span problem asks you to design a class where next(price) returns how many consecutive days (including today) the stock price has been ≤ today's price. This is the "stock span" — a classic data stream monotonic stack problem. The data stream, monotonic stack, design, and stack interview pattern is the core.
Apple, Microsoft, Meta, Amazon, Google, and Bloomberg ask this because it's the canonical monotonic stack applied to streaming data. Each call to next(price) must return in amortized O(1). The stack maintains (price, span) pairs for unanswered previous days.
Monotonic decreasing stack with span accumulation. Maintain a stack of (price, span) pairs. For next(price): initialize span=1. While stack top's price ≤ current price: pop and add its span to current span. Push (price, span). Return span.
Prices: [100,80,60,70,60,75,85].
The Online Stock Span problem illustrates why monotonic stacks are O(1) amortized: each element is pushed and popped at most once, so n calls take O(n) total. Storing the accumulated span with each stack entry is the key optimization. Practice this pattern on "streaming range queries" — Online Stock Span is the simplest example, but the same technique extends to sliding window maximum and range minimum queries.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Min Stack | Medium | Solve | |
| Design Browser History | Medium | Solve | |
| Sum of Subarray Ranges | Medium | Solve | |
| Buildings With an Ocean View | Medium | Solve | |
| Next Greater Element II | Medium | Solve |