Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Daily Temperatures

Stacksmedium

Implement `dailyTemperatures(temps)` returning, for each day, how many days until a warmer temperature (0 if none), using a monotonic stack.

Sample tests

Input: dailyTemperatures([73,74,75,71,69,72,76,73])
Output: [1,1,4,2,1,1,0,0]
Input: dailyTemperatures([30,40,50,60])
Output: [1,1,1,0]

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • A brute-force nested scan is O(n^2); the stack makes it O(n).

Learning resources

  • Wikipedia: Data structure
Approach & explanation (try first)

A monotonic decreasing stack of indices resolves each waiting day when a warmer temperature appears, in O(n) time.

Loading...
⌘/Ctrl + Enter

Run your code to see results.