awelgorithms

Daily temperatures wait days

Updated

a[i] is today's temperature. Wait days = j - i for the next strictly warmer day j, or 0 if none. That is next-greater-right distances. Pop while a[top] < a[i]; write i - top as the wait for each popped index (scan is i increasing, so wait is i - popped).

What to focus on

0 means no warmer day later, not that today is already warm. Store indices. Values come back through a[i].

Worked examples

three

a = [4, 1, 9]
  1. 9 pops 1 with wait 1
  2. 9 pops 4 with wait 2
  3. 9 leftover wait 0

Result: [2, 1, 0]

four

a = [4, 1, 9, 1]
  1. last 1 never warms
  2. 9 still 0

Result: [2, 1, 0, 0]

already hottest

a = [9]
  1. no later day

Result: [0]

Try it

Write waitDays(a). a is the list of temperatures. Return how many days until a strictly warmer day, or 0 if none. Write i - popped at pop time. [4, 1, 9] → [2, 1, 0]. [4, 1, 9, 1] → [2, 1, 0, 0]. [9, 4, 1] → [0, 0, 0].

a is a non-empty list of temperatures (integers).