Daily Temperatures

Daily Temperatures

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 i<sup>th</sup> day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead.

LeetCode Problem - 739: Link | Click Here

import java.util.Stack;

class Solution {
    // Method to calculate the number of days until warmer temperatures for each day
    public int[] dailyTemperatures(int[] temperatures) {
        // int len = temperatures.length; **  This create time complexity problem
        // int[] answer = new int[len];


        // for (int i=0; i<len; i++){
        //     int finalAns = 0;
        //     for (int j=i+1; j<len; j++){
        //         if (temperatures[j]>temperatures[i]){
        //             finalAns = j-i;
        //             break;
        //         }
        //     }

        //     answer[i] = finalAns;
        // }

        // return answer;

        int len = temperatures.length;
        int[] answer = new int[len];
        Stack<Integer> stack = new Stack<>();

        // Iterate through the temperatures array
        for (int i = 0; i < len; i++) {
            // While the stack is not empty and the current temperature is higher than the temperature
            // at the index stored in the stack, update the answer for the index and pop it from the stack
            while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) {
                int index = stack.pop();
                answer[index] = i - index;
            }

            // Push the current index onto the stack
            stack.push(i);
        }

        // The remaining indices in the stack do not have warmer temperatures ahead
        // Set their corresponding answers to 0
        while (!stack.isEmpty()) {
            answer[stack.pop()] = 0;
        }

        return answer;
    }
}

Did you find this article valuable?

Support Perf Insights by becoming a sponsor. Any amount is appreciated!