Browse curriculum

FAANGPrep Sprint

Daily Temperatures

Find how many days you have to wait for a warmer temperature.

Problem Understanding

temperatures[i] is the temperature on day i. Build an array answer where answer[i] counts the days from day i until the first strictly warmer day. If no warmer day ever comes, answer[i] stays 0.

Algorithm Strategy

We use a Monotonic Decreasing Stack.

  1. Initialize answer array with 0s.
  2. Use a stack to store indices of days.
  3. Iterate through temperatures.
  4. While the current temperature is warmer than the temperature at the index stored in stack.top():
    • We found a warmer day for stack.top()!
    • Pop the index (prevIndex).
    • Calculate days waiting: i - prevIndex.
    • Update answer[prevIndex].
  5. Push current index i onto the stack.

Interactive Visualization

8 DAYS

ANSWER = 0

temperatures · answer

73
0

0

74
0

1

75
0

2

71
0

3

69
0

4

72
0

5

76
0

6

73
0

7

stack · waiting days

empty

Waiting

0

Answered

0

 

answer starts as zeros: a day with no warmer day after it keeps 0

Next

Day 0: 73°

Temps

Visualize how the monotonic stack keeps track of 'unresolved' cooler days.