Online Stock Span — LeetCode 901 Python Solution

MediumStackDesignData StreamMonotonic Stack
Problem
#901
Pattern
Stack
Reading time
3 min

The 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.

Example

Input
["StockSpanner", "next", "next", "next", "next", "next", "next", "next"]
Output
[null, 1, 1, 1, 2, 1, 4, 6]
Explanation
StockSpanner stockSpanner = new StockSpanner();

Python solution

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

    def next(self, price: int) -> int:
        cnt = 1
        while self.stk and self.stk[-1][0] <= price:
            cnt += self.stk.pop()[1]
        self.stk.append((price, cnt))
        return cnt


# Your StockSpanner object will be instantiated and called as such:
# obj = StockSpanner()
# param_1 = obj.next(price)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 901. Online Stock Span is filed here because LeetCode tags it Stack, which is the vocabulary this hub collects.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

On a study list

This problem is on LeetCode 75.

Frequently asked questions

How hard is LeetCode 901. Online Stock Span?
LeetCode 901. Online Stock Span is rated Medium on LeetCode.
What is the time complexity of LeetCode 901. Online Stock Span?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 901. Online Stock Span?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 901. Online Stock Span cover?
LeetCode 901. Online Stock Span is tagged Stack, Design, Data Stream and Monotonic Stack on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview