LeetCode ยท #739

Daily Temperatures Solution

Given daily temperatures, return an array where answer[i] is the number of days until a warmer temperature. If no warmer day exists, answer[i] = 0.

01
Section One ยท Problem

Problem Statement

๐Ÿท๏ธ

Difficulty

Medium

๐Ÿ”—

LeetCode

Problem #739

๐Ÿ—๏ธ

Pattern

Monotonic Stack โ€” next greater element

Given an array of integers 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 with a warmer temperature, set answer[i] = 0.

Example
Input: temperatures = [73, 74, 75, 71, 69, 72, 76, 73] Output: [1, 1, 4, 2, 1, 1, 0, 0] // Day 0 (73ยฐ): next warmer is day 1 (74ยฐ) โ†’ 1 // Day 2 (75ยฐ): next warmer is day 6 (76ยฐ) โ†’ 4 days
Constraints
โ€ข 1 โ‰ค temperatures.length โ‰ค 10โต โ€ข 30 โ‰ค temperatures[i] โ‰ค 100
02
Section Two ยท Approach 1

Brute Force โ€” O(nยฒ)

For each day, scan rightward to find the first warmer day. Record the distance.

Problem: O(n) scan per day โ†’ O(nยฒ) total. A monotonic decreasing stack resolves all "waiting" days in one pass โ€” each day is pushed once and popped once for O(n).
Java โ€” Brute Force
class Solution { public int[] dailyTemperatures(int[] temps) { int[] answer = new int[temps.length]; for (int i = 0; i < temps.length; i++) for (int j = i + 1; j < temps.length; j++) if (temps[j] > temps[i]) { answer[i] = j - i; break; } return answer; } }
Python โ€” Brute Force
class Solution: def dailyTemperatures(self, temps: list[int]) -> list[int]: answer = [0] * len(temps) for i in range(len(temps)): for j in range(i + 1, len(temps)): if temps[j] > temps[i]: answer[i] = j - i break return answer
MetricValue
TimeO(nยฒ)
SpaceO(1) โ€” excluding output
03
Section Three ยท Approach 2

Monotonic Stack โ€” O(n)

Maintain a stack of indices representing days waiting for a warmer temperature. The stack is in decreasing temperature order. When a new day is warmer than the stack's top, pop and resolve โ€” the wait is current_index โˆ’ popped_index.

๐Ÿ’ก Mental model: Imagine a queue of people waiting for the sun to come out. When a warmer day arrives, everyone in the queue who was waiting for at least this much warmth steps out and records how long they waited. The remaining people (who need even more warmth) keep waiting. New arrivals join the back.
Algorithm
  • Step 1: Create an empty stack (stores indices, not temperatures).
  • Step 2: For each day i:
  • Step 3: While stack is non-empty AND temps[i] > temps[stack.peek()]: pop index j. Set answer[j] = i โˆ’ j.
  • Step 4: Push i onto the stack.
  • Step 5: Remaining stack indices get 0 (no warmer day) โ€” already initialized.
๐ŸŽฏ Monotonic stack pattern:
  • Any "next greater element" or "next smaller element" problem โ†’ monotonic stack.
  • The stack maintains a decreasing (for next-greater) or increasing (for next-smaller) order.
  • When an element breaks the monotonicity, all violated elements get their answer.
  • Each element is pushed/popped exactly once โ†’ O(n).
04
Section Four ยท Trace

Visual Walkthrough

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

Monotonic Decreasing Stack โ€” pop when warmer day found
TEMPERATURES 73 74 75 71 69 72 76 73 0 1 2 3 4 5 6 7 STACK TRACE (indices in decreasing temp order) i=0: push 0 stack: [0(73)] i=1: 74>73 โ†’ pop 0, ans[0]=1. push 1 stack: [1(74)] i=2: 75>74 โ†’ pop 1, ans[1]=1. push 2 stack: [2(75)] i=3: 71<75 โ†’ push 3 stack: [2(75), 3(71)] i=4: 69<71 โ†’ push 4 stack: [2(75), 3(71), 4(69)] i=5: 72>69 โ†’ pop 4, ans[4]=1. 72>71 โ†’ pop 3, ans[3]=2. push 5 stack: [2(75), 5(72)] i=6: 76>72 โ†’ pop 5, ans[5]=1. 76>75 โ†’ pop 2, ans[2]=4. push 6. 76 clears all! stack: [6(76)] i=7: 73<76 โ†’ push 7 stack: [6(76), 7(73)] ANSWER (remaining stack indices โ†’ 0) 1 1 4 2 1 1 0 0 Answer: [1, 1, 4, 2, 1, 1, 0, 0] โœ“
05
Section Five ยท Implementation

Code โ€” Java & Python

Java โ€” Monotonic Stack
import java.util.Stack; class Solution { public int[] dailyTemperatures(int[] temperatures) { int[] answer = new int[temperatures.length]; Stack<Integer> stack = new Stack<>(); // indices for (int i = 0; i < temperatures.length; i++) { while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) { int j = stack.pop(); answer[j] = i - j; } stack.push(i); } return answer; // remaining indices default to 0 } }
Python โ€” Monotonic Stack
class Solution: def dailyTemperatures(self, temperatures: list[int]) -> list[int]: answer = [0] * len(temperatures) stack = [] # indices for i, temp in enumerate(temperatures): while stack and temp > temperatures[stack[-1]]: j = stack.pop() answer[j] = i - j stack.append(i) return answer
06
Section Six ยท Analysis

Complexity Analysis

ApproachTimeSpaceTrade-off
Brute ForceO(nยฒ)O(1)Scan right for each day
Monotonic Stack โ† optimal O(n) O(n) Each index pushed/popped once. Stack holds waiting days.
07
Section Seven ยท Edge Cases

Edge Cases & Pitfalls

CaseInputWhy It Matters
Decreasing[76, 75, 74, 73]No warmer days โ†’ all zeros. Stack grows to size n.
Increasing[73, 74, 75, 76]Every day pops immediately โ†’ all 1s except last (0).
All same[70, 70, 70]Equal is NOT warmer โ†’ all zeros.
Single day[73]No future days โ†’ [0].
Warmer at end[73, 71, 69, 76]Day 6 resolves all waiting days at once โ€” multiple pops.
โš  Common Mistake: Using >= instead of > in the comparison. The problem asks for a strictly warmer day. If you pop on equal temperatures, you'll report a day that isn't actually warmer. Always use strict >.

โ† Back to Stack problems