Data Structures19 sections · 729 units
Open in Course

Daily Temperatures - Implementation

Complete solution

Here's the solution:

function dailyTemperatures(temperatures)
    n := length of temperatures
    answer := array of size n, all zeros
    stack := empty stack  // stores indices

    for i from 0 to n - 1
        while stack is not empty and temperatures[i] > temperatures[top of stack]
            j := pop from stack
            answer[j] := i - j
        push i onto stack

    return answer

Time: O(n)O(n). Space: O(n)O(n).