Skip to problem
←

Online Stock Span

Medium 0 attempts

Implement StockSpanner, which receives stock prices one day at a time and keeps its history between calls.

  • new StockSpanner() creates an instance with no recorded prices.
  • next(price) records today's price and returns its span: the number of consecutive days ending today whose prices are all less than or equal to today's price.

Include today, so every returned span is at least 1. Stop when you reach an earlier price that is strictly greater than today's price; do not skip that day to count older prices. Equal prices are included.

For prices [100, 80, 60, 70, 60, 75, 85], the returned spans are [1, 1, 1, 2, 1, 4, 6]. On the day priced 75, the consecutive prices [60, 70, 60, 75] qualify, but the preceding 80 stops the span.

The examples use constructorArgs = [] and operations = [["next", price], ...]. Each example creates a fresh instance, and its output lists the results of the calls in order.

Function contract

Implement the class StockSpanner. Fixtures contain constructor arguments and a list of [method, ...arguments] calls. Each fixture starts with a fresh instance.

Output: Each next(price) call returns its integer span. The displayed array contains these spans in call order.

Example 1

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

Monotonic Stack

Store pairs [price, span] in a stack with strictly decreasing prices. Each pair represents a consecutive block of days already known to have prices no greater than that pair's price.

Start today's span at one. While the top price is no greater than today's price, remove that pair and add its entire span. These blocks are consecutive, so they can be absorbed without scanning their individual days. The first remaining pair, if any, has a higher price and stops the span. Push today's combined block and return its size.

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 per call, O(n) for n calls; one call may take O(n). Each pair is pushed once and popped at most once.

Space: O(n) in the worst case of strictly decreasing prices.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript