Stock Span Problem Using Stack in DSA Python - Time & Space Complexity
We want to understand how the time taken grows when we calculate the stock span for many days.
How does the number of operations change as the list of stock prices gets bigger?
Analyze the time complexity of the following code snippet.
def calculate_span(prices):
stack = [] # stores indices
span = [0] * len(prices)
for i in range(len(prices)):
while stack and prices[stack[-1]] <= prices[i]:
stack.pop()
span[i] = i + 1 if not stack else i - stack[-1]
stack.append(i)
return span
This code calculates how many consecutive days before today the stock price was less or equal.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop runs once for each price.
- Inside loop: The while-loop pops from the stack, but each element is pushed and popped at most once.
- Dominant operation: The combined push and pop operations on the stack.
Each price is processed once, and each index is pushed and popped at most once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 (10 pushes + up to 10 pops) |
| 100 | About 200 (100 pushes + up to 100 pops) |
| 1000 | About 2000 (1000 pushes + up to 1000 pops) |
Pattern observation: Operations grow roughly in a straight line with input size.
Time Complexity: O(n)
This means the time taken grows directly in proportion to the number of days.
[X] Wrong: "The while-loop inside the for-loop makes this O(n²) because it can run many times each iteration."
[OK] Correct: Each element is pushed and popped only once, so total while-loop operations across all iterations add up to n, not n².
Understanding this problem shows you can use stacks smartly to reduce repeated work, a skill useful in many coding challenges.
"What if we used a simple nested loop without a stack? How would the time complexity change?"
Practice
Solution
Step 1: Understand the problem goal
The Stock Span Problem finds how many days before today had prices less than or equal to today's price consecutively.Step 2: Clarify what is counted
It counts consecutive days backward until a higher price is found or start is reached.Final Answer:
The number of consecutive days before the current day with price less than or equal to current day's price -> Option BQuick Check:
Span counts consecutive lower/equal prices [OK]
- Thinking it counts all previous days regardless of price
- Confusing span with price difference
- Assuming it finds max price instead
Solution
Step 1: Identify correct stack data structure
In Python, a stack is commonly implemented using a list, so an empty stack is an empty list: stack = []Step 2: Check other options
{} is a dictionary, () is a tuple (immutable), None is no value, so they are incorrect for stack.Final Answer:
stack = [] -> Option CQuick Check:
Empty list is stack [OK]
- Using {} which is a dictionary, not stack
- Using () which is immutable tuple
- Assigning None instead of a list
def calculate_span(prices):
stack = []
span = [0]*len(prices)
for i in range(len(prices)):
while stack and prices[stack[-1]] <= prices[i]:
stack.pop()
span[i] = i + 1 if not stack else i - stack[-1]
stack.append(i)
return span
print(calculate_span(prices))Solution
Step 1: Trace the loop and stack operations
For each price, pop indices with prices ⤠current price, then calculate span as distance from last higher price index or i+1 if none.Step 2: Calculate spans for each day
Day 0: stack empty, span=1; Day 1: price 80 ⤠100? No pop, span=1; Day 2: 60 ⤠80? No pop, span=1; Day 3: 70 > 60 pop index 2, span=2; Day 4: 60 ⤠70 no pop, span=1; Day 5: 75 > 60 pop index 4, 75 > 70 pop index 3, span=4; Day 6: 85 > 75 pop index 5, 85 > 100 no pop, span=6.Final Answer:
[1, 1, 1, 2, 1, 4, 6] -> Option AQuick Check:
Span array matches expected output [OK]
- Not popping all smaller or equal prices
- Calculating span as i instead of difference
- Confusing span with price values
def stock_span(prices):
stack = []
span = []
for i in range(len(prices)):
while stack and prices[stack[-1]] < prices[i]:
stack.pop()
if not stack:
span.append(i)
else:
span.append(i - stack[-1])
stack.append(i)
return span
print(stock_span([10, 4, 5, 90, 120, 80]))Solution
Step 1: Check span calculation for first day
When stack is empty, span should be i+1 (1 for first day), but code appends i (0 for first day), causing wrong span.Step 2: Confirm other parts are correct
Stack initialization and popping logic are fine; comparison operator < is acceptable; function returns span list correctly.Final Answer:
Span for first day should be 1, but code appends 0 -> Option DQuick Check:
Span for day 0 must be 1 [OK]
- Appending i instead of i+1 when stack empty
- Using wrong comparison operator causing wrong pops
- Not initializing span list properly
Solution
Step 1: Understand current comparison
Current algorithm uses <= to pop indices with prices less than or equal to current price, including equal prices in span.Step 2: Modify to exclude equal prices
To exclude equal prices, change comparison to strictly less than (<) so equal prices stop popping and are not included in span.Final Answer:
Change the comparison in while loop to prices[stack[-1]] < prices[i] -> Option AQuick Check:
Use < to exclude equal prices [OK]
- Using <= keeps equal prices included
- Adding extra conditions unnecessarily
- Assuming no change is needed
Ready to prove it?
Pass the test and this pattern moves unknown
