Discover how a simple stack can save you hours of tedious work tracking stock prices!
Why Stock Span Problem Using Stack in DSA Typescript?
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 by checking every previous day manually is like flipping back pages in a notebook for each new day.
Manually checking each previous day for every new price is slow and tiring. It wastes time and can easily cause mistakes, especially when you have many days to check.
This approach grows slower as the number of days increases, making it hard to keep up with fast-changing stock prices.
The Stock Span Problem using a stack helps by remembering important days so you don't have to check all previous days every time.
The stack keeps track of days with higher prices, letting you quickly find how many days in a row had lower or equal prices.
const spans: number[] = new Array(prices.length); 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 spans: number[] = new Array(prices.length); const stack: number[] = []; 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 quickly find stock spans for many days, making fast decisions easier and more reliable.
Traders use this to understand how long a stock price has been rising or stable, helping them decide when to buy or sell.
Manual checking is slow and error-prone for many days.
Using a stack remembers key days to speed up span calculation.
This approach handles large data efficiently and reliably.
Practice
Solution
Step 1: Understand the problem definition
The Stock Span Problem finds how many days in a row before today had prices less than or equal to today's price.Step 2: Identify what is calculated for each day
For each day, it counts consecutive previous days with prices not higher than current day.Final Answer:
The number of consecutive days before the current day with a price less than or equal to the current day's price -> Option CQuick Check:
Stock span = consecutive days with price ≤ current day price [OK]
- Thinking it finds max price overall
- Confusing span with price difference
- Calculating average price instead
Solution
Step 1: Recall the problem needs to track previous prices efficiently
We need to quickly find previous days with prices less or equal to current day.Step 2: Identify the data structure that supports last-in-first-out access
A stack allows pushing and popping previous prices to compare efficiently.Final Answer:
Stack -> Option AQuick Check:
Stack is used for last-in-first-out access [OK]
- Using queue which is FIFO, not suitable
- Using set which does not maintain order
- Using array without stack logic
[100, 80, 60, 70, 60, 75, 85]?Solution
Step 1: Calculate span for each day
Day 0: 100 -> span 1 (no previous)
Day 1: 80 ≤ 100 -> span 1
Day 2: 60 ≤ 80 -> span 1
Day 3: 70 > 60 -> span 2 (days 2 and 3)
Day 4: 60 ≤ 70 -> span 1
Day 5: 75 > 60, 70 -> span 4 (days 2,3,4,5)
Day 6: 85 > 75, 70, 80 -> span 6 (days 1 to 6)Step 2: Confirm final 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 regardless of price
- Confusing span with cumulative sum
- Miscounting days when price increases
function calculateSpan(prices: number[]): number[] {
const stack: number[] = [];
const span: number[] = [];
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 condition uses < to pop smaller prices, but equal prices should also be popped to count span correctly.Step 2: Correct the comparison operator
Change < to <= so that prices equal to current price are popped, ensuring correct span calculation.Final Answer:
The comparison operator should be <= instead of < in while condition -> Option BQuick Check:
Use <= to include equal prices in span [OK]
- Using < misses equal prices in span
- Storing prices instead of indices in stack
- Starting loop from 1 misses first day
[10, 4, 5, 90, 120, 80], how would you modify the standard Stock Span algorithm to also return the day index of the last higher price before each day? What is the output for the last higher price indices array?Solution
Step 1: Modify algorithm to track last higher price index
Along with span, store index from stack top before popping. If stack empty, store -1.Step 2: Calculate last higher price indices for each day
Day 0 (10): no previous higher -> -1
Day 1 (4): previous higher 10 at index 0 -> 0
Day 2 (5): previous higher 10 at index 0 -> 0
Day 3 (90): no previous higher -> -1
Day 4 (120): no previous higher -> -1
Day 5 (80): previous higher 120 at index 4 -> 4Final Answer:
[-1, 0, 0, -1, -1, 4] -> Option AQuick Check:
Last higher price indices match calculated values [OK]
- Returning span instead of last higher price indices
- Using price values instead of indices
- Assigning wrong indices when stack is empty
Ready to prove it?
Pass the test and this pattern moves unknown
