Skip to content

Latest commit

 

History

History
51 lines (35 loc) · 814 Bytes

File metadata and controls

51 lines (35 loc) · 814 Bytes

Daily Temperatures

Problem Link

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


Pattern

  • Stack
  • Monotonic Stack

Approach

Use a decreasing stack of indices. When a warmer day appears, resolve previous days.


Time Complexity

O(n)

Space Complexity

O(n)


Java Solution

import java.util.*;
class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        int n = temperatures.length;
        int[] ans = new int[n];
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < n; i++) {
            while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) {
                int idx = stack.pop();
                ans[idx] = i - idx;
            }
            stack.push(i);
        }
        return ans;
    }
}