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))- A. [3, 2, 1, 0, 0, 0, 1, 0] 7
- B. [3, 2, 1, 0, 0, 1, 1, 0] 8
- C. [3, 1, 2, 0, 0, 1, 0, 0] 7
- 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.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- Longest run of consecutive integers (in any order) using a hash set and starting only from numbers whose predecessor is absent. What is…
- Quickselect returns the k-th smallest element of an unsorted array in expected O(n) time. For [29, 18, 10, 32, 39, 19, 36, 13] and k = 4…
- A peak is an element larger than its neighbours (array ends count as −∞). Binary search runs on [43, 46, 49, 14, 48, 18, 24, 47, 28]…
- A fixed window of length 3 slides over s = "bcaacbccbbbbac" with a character-count array. At how many starting positions is the window an…
- For each element of [16, 4, 2, 19, 10, 6, 29, 9], find the next greater element to its RIGHT (−1 if none), using a monotonic stack. What…
- How many distinct non-empty substrings does the string "aaaaa" have, and how many substrings counted by position?