Online Stock Span solution explained

Online Stock Span asks you to build a class whose next(price) call returns today's span: how many consecutive days, counting back from today and including it, had a price no higher than today's. Keep a stack of (price, span) pairs with strictly falling prices; each new price absorbs the pairs it beats, adds their spans to its own, and is pushed as one merged pair. Each call is amortized O(1), even though a single call can pop many pairs.

By Published 8 min read

What the class must do

Prices for one stock arrive one day at a time. You write a class with a method next(price) that is called with each day's closing price, in order, and must immediately return that day's span. The span counts today plus every day directly before it, going back without a gap, on which the price was less than or equal to today's. The first higher price going backward ends the count. There is no list given up front, so the answer has to come from what earlier calls left behind.

prices: 31  27  29  25  26  33
spans:   1   1   2   1   2   6

prices: 40  40  38  40
spans:   1   2   1   4      (equal prices extend the run)
Price runs made up for this page, with the value each call returns

In the first run, 29 looks back past 27 (lower) and stops at 31 (higher), giving 2. The final 33 is the highest price so far, so its span covers all six days. In the second run, the last 40 looks back over 38 and both earlier 40s, because equal prices do not stop the count.

Worth confirming: does an equal price extend the span (in the usual statement, yes), can prices be zero or fractional (it does not change the method), and is there any limit on how many calls arrive (it decides whether the slow version is acceptable).

Why interviewers like it

It combines two skills. First, it is a small design question, so you have to decide what state the object keeps between calls rather than writing one function over an array. Second, the efficient state is a monotonic stack, which many candidates know only in its offline form. Seeing that the same idea works on a stream, and explaining the amortized cost per call, is what separates a fast answer from a correct but slow one.

First attempt: remember everything

Store every price in a list. On each call, append today's price and walk backward until you meet a higher one, counting days as you go. This is easy to get right and shows you understand the definition. It is slow when prices keep rising: every call walks all the way back to day one, so n calls cost O(n²) in total. Keep it, because it is a convenient checker.

class StockSpannerSlow:
    def __init__(self):
        self.prices = []

    def next(self, price):
        self.prices.append(price)
        span = 0
        for p in reversed(self.prices):
            if p > price:
                break
            span += 1
        return span
Python: store all prices and look back on every call. Correct, quadratic over a rising run.

The stack of merged spans

Notice what happens after a high price arrives. Say today is 29 and it beats yesterday's 27. From now on, no future day can stop its look-back at 27 without first passing 29, which is higher or equal. So 27 will never matter again as an individual day. It can be folded into 29's span. Applying that rule every day leaves a stack whose prices fall strictly from bottom to top, each carrying the number of days it absorbed. A new price pops every pair whose price is at or below it, adds their spans to its own starting value of 1, and pushes the result. Its span is that sum.

class StockSpanner:
    def __init__(self):
        self.stack = []          # (price, span); prices fall from bottom to top

    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
Python: a stack of (price, span) pairs with strictly falling prices

The comparison is less than or equal, because an equal earlier price belongs inside the span. Using strictly less than gives wrong answers on runs with repeats, such as the 40, 40, 38, 40 example, which is why that run is on this page.

class StockSpanner {
  constructor() {
    this.day = -1;
    this.prices = []; // prices on the stack, strictly falling
    this.days = [];   // the day each stacked price arrived
  }

  next(price) {
    this.day++;
    while (this.prices.length && this.prices[this.prices.length - 1] <= price) {
      this.prices.pop();
      this.days.pop();
    }
    const previousHigher = this.days.length ? this.days[this.days.length - 1] : -1;
    this.prices.push(price);
    this.days.push(this.day);
    return this.day - previousHigher;
  }
}
JavaScript: store day numbers instead of spans, and subtract

This version records the day each surviving price arrived. After popping, the top of the stack is the most recent day with a strictly higher price, so the span is simply today's day number minus that day. If the stack is empty, nothing earlier was higher, and the span reaches back to before day 0. Both designs do the same pops; pick whichever you can explain faster.

Complexity per call and overall

n calls to next()
DesignOne callAll n callsMemory
Keep every price, look backO(n) worst caseO(n²)O(n)
Stack of (price, span)O(n) worst case, O(1) amortizedO(n)O(n) worst case, on a falling run
Stack of (price, day)O(1) amortizedO(n)O(n) worst case
n calls to next(). Scroll sideways on a small screen.

A single call can still pop a lot, for example when a very high price follows a long falling run. That is why the honest phrase is amortized: every price is pushed once and popped at most once over the life of the object, so the total work for n calls is O(n) even though one call may be slow.

Cases to run by hand

  • The very first call: always 1.
  • A strictly rising run: spans 1, 2, 3 and so on, with the stack holding one pair.
  • A strictly falling run: every span is 1 and the stack keeps growing.
  • Equal prices in a row: spans 1, 2, 3, because ties extend the run.
  • A spike after a long fall: one call that pops everything and returns the full day count.

Where people slip

  • Popping only on strictly lower prices, which breaks the tie rule.
  • Pushing the price with a span of 1 instead of the merged span, so later calls undercount.
  • Recomputing from a stored list on every call and calling it O(1) because the method body is short.
  • Keeping the stack as a module-level variable instead of instance state, so two spanners share history.
  • Describing the cost as O(1) per call without the word amortized.

Likely follow-ups

  • Answer for a whole list offline: run the same stack over the array, or scan for the previous greater index of each position.
  • Strictly lower prices only: change the comparison to strictly less than and re-run the tie examples.
  • Span measured in calendar days with gaps: store dates and subtract them instead of counting calls.
  • Several stocks at once: keep one stack per ticker in a dictionary keyed by symbol.
  • Spans capped at a window of the last w days: keep the day numbers, and when the top of the stack is older than the window, clamp the span to w. The stack can then be trimmed from the bottom.

How to narrate it

Fictional example

Explaining why beaten prices can be merged
Candidate
If I store every price and look back each call, a rising run costs me n squared overall.
Candidate
But once a price is beaten by a later one that is higher or equal, it can never be where a future look-back stops. So I merge it into the newer price's span.
Candidate
That leaves a stack of pairs with falling prices. Each call pops the pairs it beats, adds up their spans plus one, and pushes the merged pair.
Interviewer
What is the cost of one call?
Candidate
One call can pop a lot, but each pair is pushed once and popped once in total, so it is constant time amortized.

This is the streaming mirror of Next Greater Element: there, a new value answers older ones; here, a new value asks about older ones. Remove K Digits keeps a stack with the opposite order to build the smallest number, and Asteroid Collision pops with a three-way comparison. For another class that keeps clever state between calls, see LRU Cache.

Rehearsing with Natively

Design questions like this one reward talking before typing, so rehearse the conversation and not only the code. In a mock session on Mac or Windows, Natively can pick up the class signature from a screenshot, suggest the merged-span stack when you are stuck on the look-back version, and save a transcript of your answer. Rereading it shows quickly whether you said amortized and handled ties. See how the coding interview assistant works.

Questions people ask

How do you solve Online Stock Span?

Keep a stack of (price, span) pairs with prices falling from bottom to top. On each call, start the span at 1, pop every pair whose price is at or below today's and add its span, then push today's price with the total and return it.

Why is Online Stock Span amortized O(1)?

Each price is pushed once and popped at most once over the life of the object. One call can pop many pairs, but n calls do at most n pops in total.

Do equal prices count in the stock span?

Yes. The span counts earlier days with a price less than or equal to today's, so the stack must pop on less than or equal, not only on strictly less.

What is the brute force for Online Stock Span?

Store every price and walk back from today until a higher price appears. It is O(n) per call and O(n squared) over a rising run of n prices.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP