Algo-Sim › Stacks & Monotonic Stack

Online Stock Span

Medium · Stacks & Monotonic Stack · step through it in Java, Python and C++ on your own input

Each call next(price) returns how many consecutive days, ending today, the price was less than or equal to today's.

Problem

Design a class that receives one stock price per day through next(price). Each call returns today's span: the number of consecutive days ending today (today included) on which the price was less than or equal to today's price.

Constraints

Edge cases to test

Follow-up questions

Why store (price, span) pairs?
Popping a smaller price adds its span, so each price is pushed and popped once: O(1) amortized per call.
What if you need spans over a window only?
Keep indices instead of spans and cap the answer at the window length.

Solution

Java

class StockSpanner {
    private final Deque<int[]> stack = new ArrayDeque<>();

    public int next(int price) {
        int span = 1;
        while (!stack.isEmpty() && stack.peek()[0] <= price) {
            span += stack.pop()[1];
        }
        stack.push(new int[] { price, span });
        return span;
    }
}

Python

class StockSpanner:
    def __init__(self):
        self.stack = []

    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

C++

#include <bits/stdc++.h>
using namespace std;

class StockSpanner {
  public:
    deque<vector<int>> stack = {};

    int next(int price) {
        int span = 1;
        while (!stack.empty() && stack.back()[0] <= price) {
            span += stack.back()[1];
            stack.pop_back();
        }
        stack.push_back(vector<int>{price, span});
        return span;
    }
};

More Stacks & Monotonic Stack problems