0:00 / 0:00

Each day, report how many days in a row the price has been at or below today's. Keep a stack of (price, span) pairs: pop every smaller price and add its span to today's. Each day is pushed and popped once: O(1) amortized.

▼

The problem

LeetCode 901 (Medium). Design a StockSpanner that receives a stock's price one day at a time; each call next(price) returns that day's span: the number of consecutive days, ending today and going back, whose price was at most today's price.

Example (LeetCode's, the walkthrough example): next(100), next(80), next(60), next(70), next(60), next(75), next(85) → 1, 1, 1, 2, 1, 4, 6.

TRY IT ON LEETCODE ▶

The solution

class StockSpanner:
    def __init__(self):
        self.stack = []  # (price, span) pairs

    def next(self, price):
        span = 1
        while self.stack and self.stack[-1][0] <= price:
            span += self.stack.pop()[1]
        self.stack.append((price, span))
        return span

Transcript

Online Stock Span. A stock's price arrives one day at a time. Each day, return its span: the number of days in a row, ending today, with a price no higher than today's.

Take the prices one hundred, eighty, sixty, seventy, sixty, seventy-five, eighty-five. Their spans are one, one, one, two, one, four, six. Look at seventy-five: sixty, seventy and sixty before it are all lower, so it reaches back four days, counting itself. Eighty is higher and stops it.

The simple way keeps every price, and each day walks back until it meets a higher one. But if prices keep rising, nothing ever stops the walk. Day n checks all n days, so the total grows like n squared.

Picture each day as a nesting doll, as tall as its price, carrying its span. When a new doll arrives, it swallows every doll at the end of the shelf that's no taller, and adds their spans to its own. Any later walk that gets past the new doll would get past those smaller ones too, so they never matter again. What's left on the shelf gets shorter toward the end: a monotonic stack.

In code, the shelf is a stack of price and span pairs. Start the span at one. While the top price is at most today's, pop it and add its span. Then push today's pair and return the span.

Let's run the example. One hundred, eighty and sixty each get one. Seventy swallows sixty, so its span is two. The next sixty is shorter than seventy: one. Seventy-five swallows sixty, then seventy: one plus one plus two is four. Eighty-five swallows seventy-five, then eighty: one plus four plus one is six. One hundred stops it.

Every price is pushed once and popped at most once. So n days take linear time: constant per call, amortized. With falling prices, nothing is swallowed, so the stack can hold all n pairs.

Swallow the shorter dolls, add their spans, push today. That's Online Stock Span.