Stock Span Problem Using Stack in DSA Java - Time & Space Complexity
We want to understand how the time needed to calculate stock spans changes as the number of days grows.
How does the number of operations grow when we process more stock prices?
Analyze the time complexity of the following code snippet.
public int[] calculateSpan(int[] prices) {
int n = prices.length;
int[] span = new int[n];
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < n; i++) {
while (!stack.isEmpty() && prices[stack.peek()] < prices[i]) {
stack.pop();
}
span[i] = stack.isEmpty() ? (i + 1) : (i - stack.peek());
stack.push(i);
}
return span;
}
This code calculates the stock span for each day using a stack to track previous higher prices.
- Primary operation: The for-loop runs once for each price, and inside it, the while-loop pops from the stack.
- How many times: Each element is pushed once and popped at most once, so total stack operations are at most 2n.
As the number of days (n) increases, the total operations grow roughly twice as fast because each price is pushed and popped once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 stack operations |
| 100 | About 200 stack operations |
| 1000 | About 2000 stack operations |
Pattern observation: Operations grow linearly with input size, doubling roughly because of push and pop.
Time Complexity: O(n)
This means the time to calculate spans grows directly in proportion to the number of days.
[X] Wrong: "The inner while-loop runs n times for each element, so the time is O(n²)."
[OK] Correct: Each element is pushed and popped only once, so total inner loop operations across all elements add up to n, not n².
Understanding this linear time solution shows you can use stacks smartly to solve problems efficiently, a skill valued 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 definition
The Stock Span Problem finds, for each day, how many consecutive days before and including the current day had stock prices less than or equal to the current day's price.Step 2: Clarify what is being counted
It counts days backward until a higher price is found or the start is reached.Final Answer:
The number of consecutive days before and including the current day with a price less than or equal to the current day's price -> Option AQuick Check:
Span counts consecutive lower/equal prices [OK]
- Confusing span with maximum price
- Counting all previous days instead of consecutive ones
- Calculating price differences instead of counts
Solution
Step 1: Identify the need for tracking previous prices
The problem requires checking previous days' prices to find the span efficiently.Step 2: Choose a data structure that supports last-in-first-out access
A stack allows pushing and popping prices or indices to quickly find the last higher price.Final Answer:
Stack -> Option DQuick Check:
Stack supports efficient previous day price checks [OK]
- Using ArrayList which is inefficient for this problem
- Choosing HashMap which doesn't maintain order
- Using Queue which is FIFO, not suitable here
[100, 80, 60, 70, 60, 75, 85] using the Stock Span algorithm?Solution
Step 1: Calculate span for each day
Day 0: 100, no previous higher price, span=1
Day 1: 80 ⤠100? Yes, but previous higher price is 100, so span=1
Day 2: 60 ⤠80? Yes, but previous higher price is 80, so span=1
Day 3: 70 > 60, span=2 (days 2 and 3)
Day 4: 60 ⤠70? Yes, but previous higher price is 70, so span=1
Day 5: 75 > 60 and 70, span=4 (days 2,3,4,5)
Day 6: 85 > 75, 70, 60, span=6 (days 1 to 6)Step 2: Confirm final span array
The span array is [1, 1, 1, 2, 1, 4, 6].Final Answer:
[1, 1, 1, 2, 1, 4, 6] -> Option AQuick Check:
Span matches consecutive lower/equal days [OK]
- Counting all previous days instead of consecutive
- Misapplying stack logic causing wrong spans
- Confusing span with price values
for (int i = 0; i < prices.length; i++) {
while (!stack.isEmpty() && prices[stack.peek()] < prices[i]) {
stack.pop();
}
span[i] = stack.isEmpty() ? i + 1 : i - stack.peek();
stack.push(i);
}Solution
Step 1: Analyze the while condition for popping stack
The condition uses < to pop indices with prices less than current price, but it should pop prices less than or equal to current price to correctly count span.Step 2: Confirm correct comparison operator
Using <= ensures all previous days with price ⤠current are popped, giving correct span.Final Answer:
The comparison operator should be <= instead of < -> Option CQuick Check:
Use <= to pop all lower or equal prices [OK]
- Using < instead of <= causing wrong spans
- Storing prices instead of indices in stack
- Starting loop at wrong index
[10, 4, 5, 90, 120, 80], what is the span array if the stack is implemented to store prices instead of indices?Solution
Step 1: Understand stack storing prices instead of indices
Without indices, we cannot calculate span as difference of indices; span calculation fails.Step 2: Resulting span values
Each day is treated as isolated, so span defaults to 1 for all days.Final Answer:
[1, 1, 1, 1, 1, 1] -> Option BQuick Check:
Stack must store indices for correct span [OK]
- Storing prices causes incorrect span calculation
- Assuming span grows without index info
- Ignoring index difference in span formula
Ready to prove it?
Pass the test and this pattern moves unknown
