Daily Temperatures
For each day, count how many days pass until a warmer one, with a stack of the days still waiting.
Given an array temperaturestemperatures[i]answeranswer[i]answer[i]
Example 1
Output: [1, 1, 4, 2, 1, 1, 0, 0]
Example 2
Output: [1, 1, 1, 0]
Example 3
Output: [1, 1, 0]
The Idea
You have probably looked at a weather forecast during a cold spell and counted the days until it gets warmer. This problem asks that question for every day in a list: how many days until it is warmer than today?
Take Example 1, [73, 74, 75, 71, 69, 72, 76, 73]
The direct way is to look ahead from every day until a warmer one shows up. But then the same days are read again and again: the searches from day 2, from day 3 and from day 4 all read the 72 on day 5. Can a single pass from left to right answer every day?
It can, if we read the days in order and keep a list of the days still waiting for a warmer one. Each new day answers every waiting day that is colder than it. But which waiting days are colder? Look at the picture below, taken when day 5 of Example 1 arrives.
In the column labelled "waiting before day 5", three days are waiting: day 2 (75), day 3 (71) and day 4 (69). Each one is colder than the day that started waiting before it. That is no accident: if day 3 had been warmer than day 2, it would have answered day 2 on arrival, and day 2 would not be waiting any more.
So the newest waiting day is always the coldest, and day 5, at 72, checks the waiting days from the newest one back. Day 4 (69) is colder, so it waited 5 - 4 = 1 day. Day 3 (71) is colder too, and waited 2 days. Day 2 (75) is warmer than 72, and any day that started waiting before it would be warmer still, so the check stops there. Day 5 then joins the list, in the box labelled "top" under "waiting after day 5".
A list where items are added and taken off at the same end, newest first, is called a stack. That end is the top, the other end is the bottom, adding an item is a push, and taking the top item off is a pop. Here the temperatures never go up from bottom to top, and a stack kept in such an order is called a
Solution Approach
How slow is the direct way, exactly? After that, turning the idea into code means settling three things: what the stack holds, when a day counts as warmer, and what happens to the days that never get one.
Looking ahead from every day
Why not simply look ahead from each day? Two loops, one inside the other, can do it: the outer one picks a day, and the inner one walks forward until it finds a warmer day. On temperatures that only go down, such as [90, 80, 70]
The stack avoids this, because each day is pushed once and popped at most once, and a popped day is never looked at again.
What the stack holds
Should the stack hold temperatures or day numbers? An answer is a distance in days, so the stack holds the day numbers, which are the positions in the array. From a day number dtemperatures[d]d
When a day counts as warmer
What if two days have the same temperature? The same temperature is not warmer, so the comparison must be a strict <[50, 50, 50]
Days that never get a warmer day
What about the days still on the stack when the last day has been read? No warmer day came after them, so their answer is 0. A new Java int
Java Solution
The method dailyTemperatures
- First, create the result array with
and call itnew int[temperatures.length] . Every entry starts at 0, which is already right for days that never see a warmer day.answer - Create the stack
as anwaiting , Java's resizable double-ended queue. ItsArrayDeque ,push andpop methods all work on its front, which serves as the top. It holds day numbers.peek - Go through the days with a
loop, wherefor is the number of the current day.day - Inside, a
loop reads the day on top withwhile , which looks without removing it. While that day is colder thanwaiting.peek() , pop it intoday and setearlier toanswer[earlier] .day - earlier - After the
loop, pushwhile , since it now waits for a warmer day of its own.day - When the
loop is done, returnfor .answer
The main
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
public class DailyTemperatures {
public static int[] dailyTemperatures(int[] temperatures) {
int[] answer = new int[temperatures.length]; // every entry starts at 0
Deque<Integer> waiting = new ArrayDeque<>(); // days still waiting for a warmer day
for (int day = 0; day < temperatures.length; day++) {
while (!waiting.isEmpty() && temperatures[waiting.peek()] < temperatures[day]) {
int earlier = waiting.pop(); // today is warmer than that day
answer[earlier] = day - earlier;
}
waiting.push(day);
}
return answer; // days left waiting keep 0
}
public static void main(String[] args) {
int[][] inputs = {
{73, 74, 75, 71, 69, 72, 76, 73},
{30, 40, 50, 60},
{30, 60, 90},
{50, 50, 50},
{90, 80, 70},
{42}
};
for (int[] temperatures : inputs) {
System.out.println(Arrays.toString(temperatures) + " -> "
+ Arrays.toString(dailyTemperatures(temperatures)));
}
}
}
Running it prints:
[73, 74, 75, 71, 69, 72, 76, 73] -> [1, 1, 4, 2, 1, 1, 0, 0]
[30, 40, 50, 60] -> [1, 1, 1, 0]
[30, 60, 90] -> [1, 1, 0]
[50, 50, 50] -> [0, 0, 0]
[90, 80, 70] -> [0, 0, 0]
[42] -> [0]
Look at the first line: day 2 gets 4. In the picture, day 2 (75) was still waiting after day 5, and only the 76 on day 6 popped it. Days 6 and 7 end with 0, because they were still on the stack when the loop finished.
The [50, 50, 50]<<=while[1, 1, 0]<=
On [90, 80, 70][42]
The original implementation,
Complexity
The work is one pass over the days, plus the pops, and a day can be popped only once.
- Time: O(n), where n is the number of days. The
loop pushes each day once, and each day is popped at most once, so all runs of thefor loop together take at most n steps.while - Space: O(n) for the stack, which holds every day when the temperatures only go down, as in
. The[90, 80, 70] array is the output, not extra space.answer
The same stack answers