Stock Span Problem Using Stack in DSA Javascript - Time & Space Complexity
We want to understand how the time needed to calculate stock spans changes as we look at more days of prices.
How does the number of operations grow when we add more stock prices?
Analyze the time complexity of the following code snippet.
function calculateSpan(prices) {
const stack = [];
const spans = [];
for (let i = 0; i < prices.length; i++) {
while (stack.length > 0 && prices[stack[stack.length - 1]] <= prices[i]) {
stack.pop();
}
spans[i] = stack.length === 0 ? i + 1 : i - stack[stack.length - 1];
stack.push(i);
}
return spans;
}
This code calculates how many consecutive days before today the stock price was less than or equal to today's price using a stack.
- Primary operation: The for-loop runs once for each price.
- Inside the loop: The while-loop pops from the stack while the current price is higher.
- Dominant operation: Each price index is pushed and popped at most once, so stack operations are key.
As we add more prices, each price is pushed once and popped once from the stack.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 stack operations (push + pop combined) |
| 100 | About 200 stack operations |
| 1000 | About 2000 stack operations |
Pattern observation: 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 prices.
[X] Wrong: "Because of the nested while inside the for-loop, the time is O(n²)."
[OK] Correct: Each element is pushed and popped only once, so total operations stay linear, not quadratic.
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 definition
The Stock Span Problem finds how many consecutive days before today had prices less than or equal to today's price.Step 2: Clarify what is calculated for each day
For each day, it counts days backward until a higher price is found or start is reached.Final Answer:
The number of consecutive days with price less or equal to current day -> Option AQuick Check:
Span counts consecutive lower/equal prices before today [OK]
- Confusing span with max or min price
- Thinking span is price difference
- Ignoring consecutive days condition
Solution
Step 1: Identify the correct data structure for stack
In JavaScript, a stack is usually implemented as an array to use push and pop methods.Step 2: Check initialization syntax
An empty array is initialized with [] which is correct for a stack.Final Answer:
const stack = []; -> Option CQuick Check:
Stack uses array [] in JavaScript [OK]
- Using object {} instead of array
- Assigning null or number instead of array
- Forgetting to initialize stack before use
[100, 80, 60, 70, 60, 75, 85] using the Stock Span Problem algorithm?Solution
Step 1: Calculate span for each price
Day 0: 100 -> span=1 (no previous days)
Day 1: 80 < 100 -> span=1
Day 2: 60 < 80 -> span=1
Day 3: 70 > 60 -> span=2 (includes day 2)
Day 4: 60 < 70 -> span=1
Day 5: 75 > 60, 70, 60 -> span=4 (days 4,3,2,1)
Day 6: 85 > 75, 70, 60, 80 -> span=6 (days 5,3,2,1,0)Step 2: Write the span array
The spans are [1, 1, 1, 2, 1, 4, 6].Final Answer:
[1, 1, 1, 2, 1, 4, 6] -> Option DQuick Check:
Span array matches calculated values [OK]
- Counting all previous days instead of consecutive
- Mixing up greater and less conditions
- Incorrectly including days with higher prices
function calculateSpan(prices) {
const stack = [];
const span = [];
for (let i = 0; i < prices.length; i++) {
while (stack.length > 0 && prices[stack[stack.length - 1]] <= prices[i]) {
stack.pop();
}
span[i] = stack.length === 0 ? i + 1 : i - stack[stack.length - 1];
stack.push(i);
}
return span;
}
Solution
Step 1: Analyze the while loop condition
The loop pops indices while the price at top index is less than or equal to current price, which is correct for span calculation.Step 2: Check span calculation formula
If stack is empty, span is i+1 (all previous days), else difference between current index and top index in stack, which is correct.Step 3: Verify stack usage
Stack stores indices, which is standard to access prices array correctly.Final Answer:
There is no error; the code correctly calculates the stock span -> Option BQuick Check:
Code matches standard stock span algorithm [OK]
- Changing < to <= breaks correct span logic
- Storing prices instead of indices causes wrong indexing
- Incorrect span formula leads to wrong results
[10, 4, 5, 90, 120, 80], how would the Stock Span Problem algorithm change if we want to find the span of days with prices strictly less than the current day's price (not less than or equal)? What is the resulting span array?Solution
Step 1: Understand the strict less than condition
Change the comparison in the algorithm from ⤠to <, so only days with price strictly less count towards span.Step 2: Calculate spans with strict less than
Day 0: 10 -> span=1
Day 1: 4 < 10 -> span=1
Day 2: 5 > 4 -> span=2 (days 1 and 2)
Day 3: 90 > 5,4,10 -> span=4 (days 0,1,2,3)
Day 4: 120 > 90 -> span=5 (days 0 to 4)
Day 5: 80 < 120 -> span=1Final Answer:
[1, 1, 2, 4, 5, 1] -> Option AQuick Check:
Strict less than span matches [1,1,2,4,5,1] [OK]
- Not changing comparison operator correctly
- Counting equal prices in span incorrectly
- Miscounting consecutive days with strict condition
Ready to prove it?
Pass the test and this pattern moves unknown
