Data Structures & AlgorithmsHardFlipkart/Uber OA · placement

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

Correct answer: B. [0, 1, 0, 1, 0, 0, 1, 0] 3

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

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

Exams that ask this topic