Stock Span Problem

medium

The span of a stock's price on day i is the number of consecutive days up to and including day i on which the price was less than or equal to the price on day i.

Given the daily prices arr, return the span for each day.

Hints

A day's span stops at the first earlier day with a strictly higher price.
So span[i] = i - (index of previous greater price).
A decreasing-price monotonic stack finds that boundary for every day.

Common doubts

They're all inside today's span (today matches or beats them), and once today sits to their right they can never be the 'previous greater' for a future day.
Every earlier day was <= today's price, so the span reaches the very start: i + 1.
Yes — the span is just the distance from each day to its previous strictly-greater price.

Interview follow-ups

The stack version already is online: it only ever looks at past days, so you can feed prices one at a time and emit each span immediately.
Pop with < instead of <=, so equal prices end the span.

Fun facts

  • The stock span is the historical origin of the 'previous greater element' pattern in algorithm texts.
  • It's an online monotonic stack — each price is processed once and never revisited.

Asked at

AmazonGoogleFlipkart
Frequently Sometimes Occasionally
Example 1
Input: arr = [100,80,60,70,60,75,85]
Output: [1,1,1,2,1,4,6]
Each day's span reaches back to the previous day with a strictly higher price.
Example 2
Input: arr = [10,4,5,90,120,80]
Output: [1,1,2,4,5,1]
Day with price 120 spans all 5 prior days; 80 (last) has span 1 because 120 > 80.
Constraints

- 1 <= arr.length <= 10^5 - 1 <= arr[i] <= 10^5

Solve this problem →