Stock Span Problem Using Stack in DSA C - Time & Space Complexity
We want to understand how the time needed to solve the stock span problem changes as the number of days grows.
Specifically, how does the algorithm handle many stock prices efficiently?
Analyze the time complexity of the following code snippet.
void calculateSpan(int prices[], int n, int span[]) {
int stack[n];
int top = -1;
for (int i = 0; i < n; i++) {
while (top >= 0 && prices[stack[top]] < prices[i]) {
top--;
}
span[i] = (top == -1) ? (i + 1) : (i - stack[top]);
stack[++top] = i;
}
}
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 day.
- Inside the loop: The while-loop pops from the stack while the current price is higher.
- How many times: Each element is pushed and popped at most once, so total stack operations are at most 2n.
As the number of days increases, each price is processed once and compared with previous prices using the stack.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 stack operations |
| 100 | About 200 stack operations |
| 1000 | About 2000 stack operations |
Pattern observation: The total operations grow roughly in a straight line with input size.
Time Complexity: O(n)
This means the time to calculate spans grows directly with the number of days, making it efficient for large inputs.
[X] Wrong: "The inner while-loop runs n times for each day, so the complexity is O(n²)."
[OK] Correct: Each price is pushed and popped only once, so total inner loop operations add up to n, not n times n.
Understanding this problem shows you can use stacks to solve real-world challenges efficiently, a skill valued in many coding tasks.
"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 how many consecutive previous days had stock prices less than or equal to the current day's price.Step 2: Identify what is calculated for each day
For each day, it counts the number of consecutive days before it with prices not greater than the current day's price.Final Answer:
The number of consecutive days with price less or equal to current day -> Option BQuick Check:
Span counts consecutive smaller/equal prices [OK]
- Confusing span with maximum price
- Calculating total sum instead of span
- Counting days with price greater than current
Solution
Step 1: Identify correct stack initialization in C
In C, stack is usually an array with an integer top initialized to -1 to indicate empty stack.Step 2: Check each option
int stack[100]; int top = -1; correctly declares an int array and sets top to -1. int stack[] = {0}; int top = 0; initializes top to 0 which is incorrect for empty stack. int *stack; top = NULL; uses pointer and NULL incorrectly. stack = new int[100]; top = -1; uses 'new' which is C++ syntax, not C.Final Answer:
int stack[100]; int top = -1; -> Option AQuick Check:
Array + top = -1 initializes empty stack in C [OK]
- Using C++ 'new' keyword in C code
- Setting top to 0 instead of -1
- Using uninitialized pointers for stack
[100, 80, 60, 70, 60, 75, 85] using the Stock Span algorithm?Solution
Step 1: Calculate span for each day
Day 0: price=100, no previous, span=1
Day 1: price=80, previous 100 > 80, span=1
Day 2: price=60, previous 80 > 60, span=1
Day 3: price=70, previous 60 ⤠70, span=1+1=2
Day 4: price=60, previous 70 > 60, span=1
Day 5: price=75, previous 60 ⤠75, count 1 (day4), previous 70 ⤠75, count 2 (day3), previous 60 ⤠75, count 3 (day2), previous 80 > 75 stop, span=4
Day 6: price=85, previous 75 ⤠85, count 1 (day5), previous 60 ⤠85, count 2 (day4), previous 70 ⤠85, count 3 (day3), previous 60 ⤠85, count 4 (day2), previous 80 ⤠85, count 5 (day1), previous 100 > 85 stop, span=6Step 2: Write 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 counts consecutive smaller/equal prices [OK]
- Counting all previous days instead of consecutive
- Ignoring equal prices in span
- Miscounting span for days with fluctuating prices
for (int i = 0; i < n; i++) {
while (top != -1 && prices[stack[top]] <= prices[i]) {
top--;
}
span[i] = (top == -1) ? (i + 1) : (i - stack[top]);
stack[++top] = i;
}Solution
Step 1: Analyze the while loop condition
The while loop pops indices from stack while the price at those indices is less than or equal to current price, which is correct for span calculation.Step 2: Check span calculation and stack push
Span is set to i+1 if stack empty, else difference between current index and top of stack index. Then current index is pushed. This matches the standard algorithm.Final Answer:
No error; code correctly calculates the stock span -> Option CQuick Check:
Standard stack-based span algorithm used [OK]
- Changing <= to < breaks span logic
- Pushing before span calculation causes wrong results
- Incorrect stack empty condition
[10, 4, 5, 90, 120, 80], how would the Stock Span algorithm change if we want to count days with strictly less price (not less or equal)? What is the resulting span array?Solution
Step 1: Understand change from ⤠to < in comparison
Changing from less or equal to strictly less means while popping from stack, we pop only if previous price is strictly less than current price, not equal.Step 2: Calculate span with strict less condition
Day 0: 10, span=1
Day 1: 4, previous 10 > 4, span=1
Day 2: 5, previous 4 < 5, pop 4, span=2
Day 3: 90, previous 5 < 90, pop 5; previous 10 < 90, pop 10; stack empty, span=4
Day 4: 120, previous 90 < 120, pop 90; stack empty, span=5
Day 5: 80, previous 120 > 80, span=1 (no pop)
But since we pop only if strictly less, equal prices would not pop. Here no equal prices affect.Final Answer:
[1, 1, 2, 4, 5, 1] -> Option DQuick Check:
Strict less changes popping condition, span updated accordingly [OK]
- Not updating while condition correctly
- Miscounting span for last day
- Assuming equal prices pop stack
Ready to prove it?
Pass the test and this pattern moves unknown
