Question
You’re given a list of daily temperatures. For each day, you need to find out how many days you'll have to wait until a warmer temperature. If there’s no warmer day ahead, just put 0
for that day.
This is like predicting the future weather — but only the wait time until it gets warmer.
Example
Input: [73, 74, 75, 71, 69, 72, 76, 73]
Output: [1, 1, 4, 2, 1, 1, 0, 0]
Explanation: For day 0 (temp 73), you’ll have to wait 1 day (temp 74). Day 2 (75) has to wait 4 days for a warmer day (76), and so on.
My Notes
- Use a stack to keep track of indices of temperatures.
- Loop backwards, starting from the last day.
- Pop values from the stack that aren’t warmer than the current temperature.
- The top of the stack (if exists) is the next warmer day.
- Time complexity:
O(n)
, since each index is pushed/popped once.
package main import ( "fmt" ) type Stack struct { items []int } func (s *Stack) Push(item int) { s.items = append(s.items, item) } func (s *Stack) Pop() { s.items = s.items[:len(s.items)-1] } func (s *Stack) Top() int { return s.items[len(s.items)-1] } func (s *Stack) Empty() bool { return len(s.items) == 0 } func dailyTemperatures(temperatures []int) []int { result := make([]int, len(temperatures)) stack := Stack{} for i := len(temperatures) - 1; i >= 0; i-- { for !stack.Empty() && temperatures[stack.Top()] <= temperatures[i] { stack.Pop() } if !stack.Empty() { result[i] = stack.Top() - i } stack.Push(i) } return result } func main() { result := dailyTemperatures([]int{73, 74, 75, 71, 69, 72, 76, 73}) fmt.Println(result) }