← All Exercises
Daily Temperatures with a Monotonic Stack
intermediatejavascript
Background
Monotonic stacks solve next-greater-element problems in one pass and appear in stock analysis, histogram areas, and scheduling.
Problem
Given an array of daily temperatures, return an array where each entry is the number of days until a strictly warmer day, or 0 if none occurs.
Input
An array of integers representing temperatures for consecutive days, length 1 to 100000.
Output
An array of the same length with waiting days, using 0 when no warmer future day exists.
Sample tests
Sample 1
Input: temperatures = [73,74,75,71,69,72,76,73]
Expected: [1,1,4,2,1,1,0,0]
Sample 2
Input: temperatures = [30,40,50,60]
Expected: [1,1,1,0]
Sample 3
Input: temperatures = [30,60,90]
Expected: [1,1,0]
Your solution
Learning objective
Maintain a monotonic stack of unresolved indices and fill answers when a larger value arrives.