less than 1 minute read

Problem Statement

leetcode problem link

My Solution [Accepted]

public class Solution {
    public int[] DailyTemperatures(int[] temperatures) {
        Stack<int> stack = new();
        int length = temperatures.Length;
        int[] res = new int[length];
        for (var i = 0; i < length; i++) {
            while (stack.Count > 0 && temperatures[stack.Peek()] < temperatures[i]) {
                int index = stack.Pop();
                res[index] = i - index;
            }
            stack.Push(i);
        }
        return res;
    }
}

Editorial

Approach 1: Monotonic Stack

class Solution:
    def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
        n = len(temperatures)
        answer = [0] * n
        stack = []

        for curr_day, curr_temp in enumerate(temperatures):
            # Pop until the current day's temperature is not
            # warmer than the temperature at the top of the stack
            while stack and temperatures[stack[-1]] < curr_temp:
                prev_day = stack.pop()
                answer[prev_day] = curr_day - prev_day
            stack.append(curr_day)

        return answer