Data Structures & AlgorithmsModerateAmazon · Microsoft OA

Problem: For each day, how many days until a strictly warmer day (0 if none)?

Problem: For each day, how many days until a strictly warmer day (0 if none)?
def wait(t):
    res, st = [0] * len(t), []
    for i, x in enumerate(t):
        while st and t[st[-1]] < x:
            j = st.pop(); res[j] = i - j
        st.append(i)
    return res
print(wait([30, 38, 30, 36, 35, 40, 28]))
What is printed?
  1. A. [1, 4, 1, 2, 1, 0, 1]
  2. B. [1, 3, 1, 2, 1, 0, 0]
  3. C. [1, 4, 2, 2, 1, 0, 0]
  4. D. [1, 4, 1, 2, 1, 0, 0]

Correct answer: D. [1, 4, 1, 2, 1, 0, 0]

The stack holds days still waiting for a warmer one. 38 waits until 40 at index 5 (4 days); 36 waits 2 days for 40; the last day 28 never finds a warmer day, so it stays 0.

More Coding Interview Problems questions

Exams that ask this topic