DevPath

← All problems

Daily Temperatures

Medium stack · arrays

Description

For each day, return how many days you must wait until a warmer temperature. If none, use 0.

Constraints

1 <= n <= 100000

Examples

Input: temps = [73,74,75,71,69,72,76,73]

Output: [1,1,4,2,1,1,0,0]

Hints (1)
  • Keep a decreasing stack of indices; resolve when a warmer day arrives.

Solutions

Monotonic decreasing stack of indices. · Time O(n) · Space O(n)

func dailyTemperatures(temps []int) []int {
    out := make([]int, len(temps))
    stack := []int{}
    for i, t := range temps {
        for len(stack) > 0 && t > temps[stack[len(stack)-1]] {
            j := stack[len(stack)-1]
            stack = stack[:len(stack)-1]
            out[j] = i - j
        }
        stack = append(stack, i)
    }
    return out
}

Create a free account to submit solutions, track progress and save problems.

Create account