Back to the 100
Problem 087Stack
Medium

Daily Temperatures

087

For each day, return how many days until a warmer temperature, or 0 if none exists.

EXAMPLES

Example 1
Input
{
  "temperatures": [
    73,
    74,
    75,
    71,
    69,
    72,
    76,
    73
  ]
}

Output
[
  1,
  1,
  4,
  2,
  1,
  1,
  0,
  0
]

FUNCTION SHAPE

temperatures: intArrayintArray
SOLUTION NOTE

The answer is the difference between the index of the next greater element and the current element.

Reveal reference solution +
pythonREFERENCE
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
    stack = []
    n = len(temperatures)
    res = [0] * n
    for i in range(n):
        while stack and temperatures[stack[-1]] < temperatures[i]:
            idx = stack.pop()
            res[idx] = i - idx
        stack.append(i)
    return res
TimeO(n)
SpaceO(n)
Open on LeetCode
00:00
3 local tests readyRun with ⌘/Ctrl + Enter. Your code stays in this browser.

Runs solve(...) locally in a browser worker. SWE Playbook does not submit your code. Only run code you trust; Python code may access the network.