Online Stock Span Medium 0 attempts
LeetCode ↗

Online Stock Span

Medium Stack&Queue LeetCode

Design a class that processes daily stock prices one at a time and, for each new price, reports its span — the count of consecutive days ending today (today included) during which the price never exceeded today's price.

Input Format
Implement the class StockSpanner. Fixtures contain constructor arguments and a list of [method, ...arguments] calls. Each fixture starts with a fresh instance.
Output Format
Return the specified result from each method. The displayed output lists results in call order; undefined results appear as null.

Sample Input and Output

Example 1 · Run Sample

Input
constructorArgs = []
operations = [["next",100],["next",80],["next",60],["next",70],["next",60],["next",75],["next",85]]
Output
[1,1,1,2,1,4,6]

Example 2

Input
constructorArgs = []
operations = [["next",100],["next",100],["next",100]]
Output
[1,2,3]
Constraints
  • 1 <= price <= 10^5
  • At most 10^4 calls to next
Test Cases (2)
Case 1
Args: [[],[["next",100],["next",80],["next",60],["next",70],["next",60],["next",75],["next",85]]] Expected: [1,1,1,2,1,4,6]
Case 2
Args: [[],[["next",100],["next",100],["next",100]]] Expected: [1,2,3]
Topics

Monotonic Stack

javascript
class StockSpanner {
  constructor() { this.stack = []; }
  next(price) {
    let span = 1;
    while (this.stack.length && this.stack[this.stack.length-1][0] <= price)
      span += this.stack.pop()[1];
    this.stack.push([price, span]);
    return span;
  }
}

Time: O(1) amortized | Space: O(n)

Saved in this browser only. Private to you.

JavaScript