Daily Temperatures

Medium
monotonic-stack

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-th day to get a warmer temperature.

If there is no future day for which this is possible, keep answer[i] == 0 instead.

Key Insight: This is a classic "next greater element" problem where we need the distance instead of the value. Use a monotonic decreasing stack storing indices. When we pop an index, the distance to the warmer day is current_index - popped_index.

Example 1

Input: temperatures = [73,74,75,71,69,72,76,73]
Output: [1,1,4,2,1,1,0,0]
Explanation: Day 0 (73): wait 1 day for 74. Day 2 (75): wait 4 days for 76. Day 6-7: no warmer day.

Example 2

Input: temperatures = [30,40,50,60]
Output: [1,1,1,0]
Explanation: Each day (except last) waits exactly 1 day for the next warmer temperature.

Example 3

Input: temperatures = [30,60,90]
Output: [1,1,0]
Explanation: Strictly increasing temperatures mean each day waits 1 day (except the last).

Constraints

  • 1 <= temperatures.length <= 10^5
  • 30 <= temperatures[i] <= 100
Show Hints (4)
Hint 1: What information do we need when we find a warmer day? The index of the cooler day waiting.
Hint 2: A stack of indices (not temperatures) allows us to calculate waiting days.
Hint 3: When temperature[i] > temperature[stack.top()], we found a warmer day for stack.top().
Hint 4: The answer for popped index is i - poppedIndex.
Loading editor...

Test Results

Click "Run" to execute your code against test cases

AI Tutor

Socratic guidance - I'll ask questions, not give answers

AI Tutor
Hello! I'm your AI tutor, here to guide you through this problem using the Socratic method. I won't give you direct answers, but I'll ask questions and provide hints to help you discover the solution yourself. What's your first instinct when you look at this problem? What approach comes to mind?