150NeetCode 150

25.Daily Temperatures

MediumStack ยท 5/7

Problem

Given an array temperatures of daily temperatures, return an array answer where answer[i] is the number of days you must wait after day i to get a strictly warmer temperature. If no future day is warmer, answer[i] = 0.

Examples

Input:  temperatures = [73, 74, 75, 71, 69, 72, 76, 73]
Output: [1, 1, 4, 2, 1, 1, 0, 0]
Explanation: Day 2 (75) waits until day 6 (76) โ†’ 4 days.
             Day 3 (71) waits until day 5 (72) โ†’ 2 days.
Input:  temperatures = [30, 40, 50, 60]
Output: [1, 1, 1, 0]
Input:  temperatures = [30, 60, 90]
Output: [1, 1, 0]

Constraints

  • 1 <= temperatures.length <= 10^5
  • 30 <= temperatures[i] <= 100

๐Ÿ’ก Key Insight

This is a next greater element problem. Days that are still waiting for a warmer day always form a decreasing sequence of temperatures (if a later day were warmer, the earlier one would already be resolved). Keep those waiting days on a stack: each new day pops โ€” and answers โ€” every waiting day colder than itself. Every index is pushed and popped once, so the whole thing is O(n).

Brute Force

TimeO(nยฒ)SpaceO(1)

Intuition

For each day, look forward one day at a time until a warmer temperature appears.

Algorithm

  1. For each i:
    • For j from i + 1 to n - 1: if temperatures[j] > temperatures[i], set answer[i] = j - i and break.
  2. Return answer (unresolved entries stay 0).

Visualization

temps = [73, 74, 75, 71, 69, 72, 76, 73]

i=2 (75): 71 โœ—, 69 โœ—, 72 โœ—, 76 โœ“ โ†’ 6 - 2 = 4
i=3 (71): 69 โœ—, 72 โœ“             โ†’ 5 - 3 = 2

Code

java
class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        int n = temperatures.length;
        int[] answer = new int[n];
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                if (temperatures[j] > temperatures[i]) {
                    answer[i] = j - i; // first warmer day
                    break;
                }
            }
        }
        return answer;
    }
}

Complexity

  • Time: O(nยฒ) โ€” a strictly decreasing input makes every day scan to the end.
  • Space: O(1) โ€” excluding the output array.

Complexity Comparison

Approach Time Space (excl. output)
Brute Force O(nยฒ) O(1)
Monotonic Stack O(n) O(n)
Backward Jumps O(n) O(1)

Common Pitfalls

  • Using >= instead of > when popping โ€” an equal temperature is not warmer.
  • Pushing temperatures instead of indices onto the stack; you need the index to compute the distance i - j.
  • In the backward pass, looping forever when answer[j] == 0 โ€” that means "no warmer day", so stop instead of adding 0.
  • Forgetting that days left on the stack at the end must stay 0 (Java arrays default to 0, so no extra work is needed).