EasyPythonJavaScriptTypeScript
Monotonic Stack — Daily Temperatures
Data StructuresStackArrays
Given an array temps of daily temperatures, return an array answer whereanswer[i] is the number of days you have to wait after day i to get a
warmer temperature. If there is no warmer day, answer[i] is 0.
The brute force (scan forward from every day) is O(n²). Get it to O(n) with a
stack of indices whose temperatures are still waiting for a warmer day.
Examples
solve([73, 74, 75, 71, 69, 72, 76, 73]) → [1, 1, 4, 2, 1, 1, 0, 0]
solve([30, 40, 50, 60]) → [1, 1, 1, 0]
solve([30, 60, 90]) → [1, 1, 0]Constraints
1 <= temps.length <= 100000- "Warmer" means strictly greater — an equal temperature does not count.
Sample tests
Test #1The classic example
Input: [[73,74,75,71,69,72,76,73]]
Output: [1,1,4,2,1,1,0,0]
Test #2Strictly rising — every answer is 1 except the last
Input: [[30,40,50,60]]
Output: [1,1,1,0]
Test #3Three rising days
Input: [[30,60,90]]
Output: [1,1,0]