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 temperatures, where temperatures[i] is the temperature on day i, return an array answer of the same length. answer[i] is the number of days you have to wait after day i to get a warmer temperature. If no later day is warmer, answer[i] is 0.

Example 1
Input: temperatures = [73, 74, 75, 71, 69, 72, 76, 73]
Output: [1, 1, 4, 2, 1, 1, 0, 0]
Example 2
Input: temperatures = [30, 40, 50, 60]
Output: [1, 1, 1, 0]
Example 3
Input: temperatures = [30, 60, 90]
Output: [1, 1, 0]
Solution

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], with the days numbered from 0. Day 0 is 73, and day 1 is already 74, so day 0 waits 1 day. Day 2 is 75, and the next three days, 71, 69 and 72, are all colder. Only day 6, at 76, is warmer, so day 2 waits 6 - 2 = 4 days. Days 6 and 7 never see anything warmer, so they get 0.

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.

Example 1 at day 5, temperature 72. Days 4 (69) and 3 (71) are waiting on top of day 2 (75). 72 is warmer than both, so day 4 waited 1 day and day 3 waited 2 days. They leave the waiting list, day 2 stays, and day 5 joins on top.

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 monotonic stack.

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], no inner walk ever finds one, so each walks to the end of the array. For n days that is about n²/2 steps, roughly 5 billion for 100,000 days.

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 d, temperatures[d] gives its temperature back, and today's number minus d gives how long it waited.

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 <. With [50, 50, 50], no day is warmer than another, so every answer is 0. The equal days simply wait on the stack next to each other.

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 array starts with every entry set to 0, so these days need no extra step.

Java Solution

The method dailyTemperatures works in these steps:

  1. First, create the result array with new int[temperatures.length] and call it answer. Every entry starts at 0, which is already right for days that never see a warmer day.
  2. Create the stack waiting as an ArrayDeque, Java's resizable double-ended queue. Its push, pop and peek methods all work on its front, which serves as the top. It holds day numbers.
  3. Go through the days with a for loop, where day is the number of the current day.
  4. Inside, a while loop reads the day on top with waiting.peek(), which looks without removing it. While that day is colder than day, pop it into earlier and set answer[earlier] to day - earlier.
  5. After the while loop, push day, since it now waits for a warmer day of its own.
  6. When the for loop is done, return answer.

The main method runs the three examples, three equal temperatures, temperatures that only go down, and a single day.

Java
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:

Output
[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] line shows the strict < at work: equal days stay waiting, and all three get 0. With <= in the while condition instead, the same program prints [1, 1, 0] for that line, counting an equal day as warmer. The three examples still come out right with <=, so they alone would not catch it.

On [90, 80, 70] nothing is ever popped, and the stack ends up holding all three days. [42] has no later day at all, so its only answer is 0.

The original implementation, DailyTemperatures.java, is on GitHub.

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 for loop pushes each day once, and each day is popped at most once, so all runs of the while loop together take at most n steps.
  • Space: O(n) for the stack, which holds every day when the temperatures only go down, as in [90, 80, 70]. The answer array is the output, not extra space.

The same stack answers Next Greater Element I, which looks values up in a second array.