Online Stock Span - Problem

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.

For example:

  • If the prices in the last four days were [7,2,1,2] and today's price is 2, then the span is 4 because all 4 consecutive days had prices ≤ 2.
  • If the prices in the last four days were [7,34,1,2] and today's price is 8, then the span is 3 because the last 3 days had prices ≤ 8 (but day 4 had price 34 > 8).

Implement the StockSpanner class:

  • StockSpanner() Initializes the object
  • int next(int price) Returns the span of the stock's price given that today's price is price

Input & Output

Example 1 — Basic Stock Prices
$ Input: prices = [100,80,60,70,60,75,85]
Output: [1,1,1,2,1,4,6]
💡 Note: Day 1: price=100, span=1 (just today). Day 2: price=80, span=1 (80<100). Day 3: price=60, span=1 (60<80). Day 4: price=70, span=2 (70≥60, 70<80). Day 5: price=60, span=1 (60<70). Day 6: price=75, span=4 (75≥60,70,60, 75<80). Day 7: price=85, span=6 (85≥75,60,70,60,80, 85<100).
Example 2 — Increasing Prices
$ Input: prices = [10,20,30,40]
Output: [1,2,3,4]
💡 Note: Each day has a higher price, so the span includes all previous days plus today.
Example 3 — Decreasing Prices
$ Input: prices = [40,30,20,10]
Output: [1,1,1,1]
💡 Note: Each day has a lower price than the previous, so span is always 1 (just today).

Constraints

  • 1 ≤ prices.length ≤ 104
  • 1 ≤ prices[i] ≤ 105

Visualization

Tap to expand
Stock Span Problem: Count Consecutive Days ≤ Current PricePrices:100806070607585Spans:1112146For price 85: Count days where price ≤ 8585≥75✓, 85≥60✓, 85≥70✓, 85≥60✓, 85≥80✓, 85<100✗Span = 6 (current + 5 previous days)Challenge: Do this efficiently for streaming data
Understanding the Visualization
1
Input
Stream of daily stock prices: [100,80,60,70,60,75,85]
2
Process
For each price, count consecutive days ≤ current price
3
Output
Spans: [1,1,1,2,1,4,6]
Key Takeaway
🎯 Key Insight: Use a monotonic stack to skip irrelevant days and achieve O(1) amortized time per query
Asked in
Google 25 Amazon 18 Microsoft 15 Facebook 12
125.0K Views
Medium Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen