Discover how a simple stack can save you hours of tedious price checking!
Why Stock Span Problem Using Stack in DSA Javascript?
Imagine you are tracking daily stock prices on paper. For each day, you want to know how many consecutive previous days had prices less than or equal to today's price.
Doing this manually means checking every previous day one by one, which is slow and tiring.
Manually checking each previous day's price for every new day means repeating many comparisons again and again.
This takes a lot of time and can easily cause mistakes, especially with many days of data.
The Stock Span Problem using a stack helps by remembering only important days' prices and their positions.
This way, you quickly find how many days back the price was lower without checking every single day.
for (let i = 0; i < prices.length; i++) { let span = 1; for (let j = i - 1; j >= 0 && prices[j] <= prices[i]; j--) { span++; } spans[i] = span; }
const stack = []; for (let i = 0; i < prices.length; i++) { while (stack.length && prices[stack[stack.length - 1]] <= prices[i]) { stack.pop(); } spans[i] = stack.length ? i - stack[stack.length - 1] : i + 1; stack.push(i); }
This method lets you calculate stock spans efficiently, even for large data, saving time and avoiding errors.
Traders use this to quickly understand how long a stock price has been rising, helping them decide when to buy or sell.
Manual checking is slow and error-prone for large data.
Using a stack remembers key days to speed up span calculation.
This approach is efficient and practical for real stock analysis.
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
