Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: For each day's temperature, find how many days you must wait for a warmer day (0 if never).

Problem: For each day's temperature, find how many days you must wait for a warmer day (0 if never).
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, 32, 31, 31, 35, 29, 30]))
What is printed?
  1. A. [1, 3, 1, 1, 0, 1, 0]
  2. B. [1, 2, 2, 1, 0, 1, 0]
  3. C. [1, 3, 2, 1, 0, 1, 0]
  4. D. [1, 3, 2, 1, 0, 0, 0]

Correct answer: C. [1, 3, 2, 1, 0, 1, 0]

A stack keeps indices with non-increasing temperatures; a warmer day pops them and fills their wait. 32 waits until 35 (3 days); both 31s also wait for 35 (2 and 1 days) because equal is not warmer. 29 waits 1 day for 30. Each index is pushed and popped once: O(n).

More Coding Interview Problems questions

Exams that ask this topic