Daily Temperatures
Medium stack · arrays
Description
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
}
Monotonic decreasing stack of indices. · Time O(n) · Space O(n)
function dailyTemperatures(temps) {
const n = temps.length, out = new Array(n).fill(0), stack = [];
for (let i = 0; i < n; i++) {
while (stack.length && temps[i] > temps[stack[stack.length - 1]]) {
const j = stack.pop();
out[j] = i - j;
}
stack.push(i);
}
return out;
}
Monotonic decreasing stack of indices. · Time O(n) · Space O(n)
function dailyTemperatures($temps) {
$n = count($temps); $out = array_fill(0, $n, 0); $stack = [];
for ($i = 0; $i < $n; $i++) {
while ($stack && $temps[$i] > $temps[end($stack)]) {
$j = array_pop($stack);
$out[$j] = $i - $j;
}
$stack[] = $i;
}
return $out;
}
Monotonic decreasing stack of indices. · Time O(n) · Space O(n)
def dailyTemperatures(temps):
out = [0] * len(temps)
stack = []
for i, t in enumerate(temps):
while stack and t > temps[stack[-1]]:
j = stack.pop()
out[j] = i - j
stack.append(i)
return out
Monotonic decreasing stack of indices. · Time O(n) · Space O(n)
function dailyTemperatures(temps: number[]): number[] {
const n = temps.length, out = new Array(n).fill(0), stack: number[] = [];
for (let i = 0; i < n; i++) {
while (stack.length && temps[i] > temps[stack[stack.length - 1]]) {
const j = stack.pop()!;
out[j] = i - j;
}
stack.push(i);
}
return out;
}
Create a free account to submit solutions, track progress and save problems.
Create account