MrainW's Home

All things come to those who wait!

0%

LeetCode 739. Daily Temperatures

Question

Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead.

https://leetcode.com/problems/daily-temperatures/

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
int n = temperatures.length, res[] = new int[n];
Stack<Integer> stack = new Stack<>();
for (int i = n - 1; i >= 0; i--){
while (!stack.isEmpty() && temperatures[i] >= temperatures[stack.peek()]) stack.pop();
res[i] = stack.isEmpty() ? 0 : stack.peek() - i;
stack.push(i);
}
return res;
}
}

Time complexity: O(n)

Space complexity: O(n)

Welcome to my other publishing channels