Data Structures & AlgorithmsHardProduct placement · Amazon/Microsoft

For each day, a monotonic stack finds how many days you must wait for a strictly warmer temperature (0 if never). What is printed?

For each day, a monotonic stack finds how many days you must wait for a strictly warmer temperature (0 if never). What is printed?
t = [39, 35, 33, 40, 34, 33, 38, 40]
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)
print(res, sum(res))
  1. A. [3, 2, 1, 0, 1, 2, 1, 0] 10
  2. B. [3, 2, 1, 4, 2, 1, 1, 0] 14
  3. C. [3, 2, 0, 1, 2, 1, 1, 0] 10
  4. D. [3, 2, 1, 0, 2, 1, 1, 0] 10

Correct answer: D. [3, 2, 1, 0, 2, 1, 1, 0] 10

Indices wait on the stack until a strictly higher temperature arrives; equal temperatures do not count as warmer. Output: [3, 2, 1, 0, 2, 1, 1, 0] 10.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic