StackMedium

Stock Span Visualizer

What is Stock Span

The span of a day is how many consecutive days, ending today, have a price less than or equal to today's price.

Approach

Pop days whose price is less than or equal to today. The span is the distance back to the new top, or i+1 if the stack is empty.

Visualization & algorithm

Prices and the span written so far
while top price <= today: pop
if stack is empty: span = i + 1
else: span = i - top index
push i
Step 0/0 Answer —

The finished picture is on screen when the page opens. Next and Play start from the first step. The controls sit under the picture and the pseudocode.

Complexity

PieceCostWhy
TimeO(n)Each day is pushed and popped once.
SpaceO(n)A strictly falling price list fills the stack.

Implementation

def solve(self, prices):
    st, ans = [], []
    for i, p in enumerate(prices):
        while st and prices[st[-1]] <= p:
            st.pop()
        ans.append(i + 1 if not st else i - st[-1])
        st.append(i)
    return ans