Watch 10 video solutions for Online Stock Span, a medium level problem involving Stack, Design, Monotonic Stack. This walkthrough by codestorywithMIK has 49,415 views views. Want to try solving it yourself? Practice on FleetCode or read the detailed text solution.
Design an algorithm that collects daily price quotes for some stock and returns the span of that stock's price for the current day.
The span of the stock's price in one day is the maximum number of consecutive days (starting from that day and going backward) for which the stock price was less than or equal to the price of that day.
[7,2,1,2] and the price of the stock today is 2, then the span of today is 4 because starting from today, the price of the stock was less than or equal 2 for 4 consecutive days.[7,34,1,2] and the price of the stock today is 8, then the span of today is 3 because starting from today, the price of the stock was less than or equal 8 for 3 consecutive days.Implement the StockSpanner class:
StockSpanner() Initializes the object of the class.int next(int price) Returns the span of the stock's price given that today's price is price.
Example 1:
Input ["StockSpanner", "next", "next", "next", "next", "next", "next", "next"] [[], [100], [80], [60], [70], [60], [75], [85]] Output [null, 1, 1, 1, 2, 1, 4, 6] Explanation StockSpanner stockSpanner = new StockSpanner(); stockSpanner.next(100); // return 1 stockSpanner.next(80); // return 1 stockSpanner.next(60); // return 1 stockSpanner.next(70); // return 2 stockSpanner.next(60); // return 1 stockSpanner.next(75); // return 4, because the last 4 prices (including today's price of 75) were less than or equal to today's price. stockSpanner.next(85); // return 6
Constraints:
1 <= price <= 105104 calls will be made to next.Problem Overview: Design a class that receives stock prices one by one and returns the span for each price. The span is the number of consecutive days (including today) where the price was less than or equal to today's price.
Approach 1: Using a Stack to Track Prices and Spans (Amortized O(1) per call, O(n) total)
This approach uses a stack to store previous prices along with their computed spans. When a new price arrives, repeatedly pop elements from the stack while their price is less than or equal to the current price. Each popped element contributes its span to the current day's span. Push the current price with its final span back onto the stack. The stack remains monotonic decreasing by price, which guarantees each price is pushed and popped at most once, resulting in O(n) total time for n calls and O(n) space.
The key insight is that once a smaller price is merged into a larger price's span, it never needs to be checked again. This compression avoids scanning backward through all previous prices. The pattern is a classic monotonic stack problem where the structure maintains decreasing order to quickly discard irrelevant elements.
Approach 2: Optimized Data Storage with Tuple for Price-Spans (Amortized O(1) per call, O(n) total)
This variant stores pairs like (price, span) directly in the stack instead of maintaining separate structures. When a new price arrives from the data stream, initialize the span as 1. While the stack top has a price less than or equal to the current price, pop it and add its span to the current span. Push the merged tuple back onto the stack.
The behavior is identical to the previous method but keeps the implementation compact and cache-friendly. Each stack element summarizes a block of consecutive days with prices lower than the next greater element. This ensures that span aggregation happens in chunks instead of day-by-day comparisons. Time complexity remains amortized O(1) per next() call and space complexity is O(n) to store past price groups.
Both implementations rely on the same principle used in many stack-based problems: maintain a structure that removes dominated elements immediately. Once a higher price appears, smaller historical prices become irrelevant for future span calculations.
Recommended for interviews: The monotonic stack approach with (price, span) pairs is what interviewers typically expect. A brute-force scan backward shows understanding but runs in O(n) per query. The stack-based design demonstrates knowledge of amortized analysis and efficient data structures for streaming inputs.
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Backward Scan (Brute Force) | O(n) per query | O(n) | Conceptual baseline or very small input sizes |
| Stack Tracking Prices and Spans | O(1) amortized per call, O(n) total | O(n) | General optimal solution for streaming price updates |
| Tuple-Based Monotonic Stack | O(1) amortized per call, O(n) total | O(n) | Cleaner implementation storing (price, span) pairs |