Data Structures & AlgorithmsHardTCS Digital · Infosys SP

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 = [35, 31, 30, 36, 33, 30, 31, 31]
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, 0, 0, 1, 0] 7
  2. B. [3, 2, 1, 0, 0, 1, 1, 0] 8
  3. C. [3, 1, 2, 0, 0, 1, 0, 0] 7
  4. D. [3, 2, 1, 0, 0, 1, 0, 0] 7

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

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

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

Exams that ask this topic