Dsa
Monotonic Stack
Easy
Stock Price Memory
An investor wants to know how long it has been since the stock price was last strictly higher than it is today. For each day, find the number of days between the current day and the nearest previous day that had a strictly higher price. If no such day exists, output the current day's index (0-based) as the distance to 'the start of time'.
Example:
Prices: [50, 60, 55, 58, 70, 65]
- Day 0 (50): No prev higher. Dist: 0.
- Day 1 (60): No prev higher. Dist: 1.
- Day 2 (55): Day 1 was 60. Dist: 2 - 1 = 1.
- Day 3 (58): Day 1 was 60. Dist: 3 - 1 = 2.
- Day 4 (70): No prev higher. Dist: 4.
- Day 5 (65): Day 4 was 70. Dist: 5 - 4 = 1.
Result: 0 1 1 2 4 1
Key concepts
monotonic_stackdistance_calculation
Practise this out loud — free
Start a mock interview on THIS exact question — a voice AI interviewer opens with it, pushes back like a real onsite, then hands you an instant scorecard.
🎙 Practise this question now