Asked at

Daily Temperatures

Medium
Verified
Monotonic StackStack~20 min

Given daily temperatures, return an array where each entry is the number of days to wait until a warmer day, or 0 if none follows.

Keep a monotonic stack of unresolved day indices; pop and record the gap when a warmer day arrives.

The input is a single array temperatures.

Examples

in[73, 74, 75, 71, 69, 72, 76, 73]
out[1, 1, 4, 2, 1, 1, 0, 0]

Each entry is the days to wait for a warmer temperature; 0 if none comes.

in[30, 40, 50, 60]
out[1, 1, 1, 0]

Each day warms the next, so wait one day; the last never warms.

Constraints

  • 1 ≤ temperatures.length ≤ 10⁵
  • 30 ≤ temperatures[i] ≤ 100
  • Target: O(n) time.

Get help

🔑

Sign in to solve

Sign in to write, run, and submit your solution — and to pick up where your iOS flow left off.