DSA

Online Stock Span

Stacks & Queues problem — solution with code and analysis.

August 8, 2026

Practice Link

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.

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.

Approach#

Use a monotonic stack of (price, span) pairs. When next(price) is called, start with a span of 1. Pop every pair from the stack whose price is <= the current price, accumulating their spans — this is valid because those days were themselves already consecutive days going backward from their own position. Push the current (price, accumulated span) pair and return the span. This amortizes to O(1) per call because each pair is pushed and popped at most once.

cpp
class StockSpanner {
public:
    stack<pair<int,int>> stk;
    StockSpanner() {
        
    }
    
    int next(int price) {
        int ans = 1;
        while(!stk.empty() && stk.top().first <= price)
        {
            ans += stk.top().second;
            stk.pop();
        }
        stk.push({price, ans});
        return ans;
    }
};