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.
This approach utilizes a stack to track the prices and their corresponding spans. For each new price, we compare it with the top of the stack, which holds the last price and its span. If the new price is higher or equal, we pop from the stack and add the span of the popped element to the current span count. This way, we efficiently calculate the span while ensuring that older prices do not need to be recalculated unnecessarily.
The Python solution uses a list as a stack to store pairs of prices and their spans. For each new price, we initialize the span to 1 and add it to the span of any previous prices from which it is greater or equal, thus ensuring we only process each element once as they are popped from the stack. This makes it efficient for handling up to 10,000 calls.
Python
JavaScript
Time Complexity: O(n), where n is the number of calls to next() because each element is pushed and popped from the stack at most once.
Space Complexity: O(n) for storing the stack.
This approach optimizes memory and simplifies the logic by storing prices along with pre-calculated spans in a tuple or similar structure. This implementation minimizes redundant span computation by leveraging tuple structures efficiently, ideal for platforms that can handle tuple operations swiftly.
The Java solution uses a stack of integer arrays to store prices and their computed spans. When searching for the span for a new price, it checks against the top element of the stack and if the top element's price is less than or equal to the new price, it pops the stack and increases the span accordingly. Finally, it pushes the new price and its span onto the stack.
Time Complexity: O(n), as each element is only processed once.
Space Complexity: O(n), where n is the number of calls, due to stack storage.
Based on the problem description, we know that for the current day's price price, we start from this price and look backwards to find the first price that is larger than this price. The difference in indices cnt between these two prices is the span of the current day's price.
This is actually a classic monotonic stack model, where we find the first element larger than the current element on the left.
We maintain a stack where the prices from the bottom to the top of the stack are monotonically decreasing. Each element in the stack is a (price, cnt) data pair, where price represents the price, and cnt represents the span of the current price.
When the price price appears, we compare it with the top element of the stack. If the price of the top element of the stack is less than or equal to price, we add the span cnt of the current day's price to the span of the top element of the stack, and then pop the top element of the stack. This continues until the price of the top element of the stack is greater than price, or the stack is empty.
Finally, we push (price, cnt) onto the stack and return cnt.
The time complexity is O(n), and the space complexity is O(n). Here, n is the number of times next(price) is called.
| Approach | Complexity |
|---|---|
| Using a Stack to Track Prices and Spans | Time Complexity: O(n), where n is the number of calls to next() because each element is pushed and popped from the stack at most once. |
| Optimized Data Storage with Tuple for Price-Spans | Time Complexity: O(n), as each element is only processed once. |
| Monotonic Stack | — |
| 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 |
Online Stock Span (Microsoft, Amazon, FactSet, Samsung, Adobe, Flipkart) : Explanation ➕ Live Coding • codestorywithMIK • 49,415 views views
Watch 9 more video solutions →Practice Online Stock Span with our built-in code editor and test cases.
Practice on FleetCode