Data Structures & AlgorithmsVery hardCodeforces Div2 D · TCS NQT
A monotonic deque computes the minimum of each window of size 3.
A monotonic deque computes the minimum of each window of size 3.
from collections import deque
a = [4, 2, 12, 11, -5, 7]
k = 3
dq = deque(); out = []
for i, x in enumerate(a):
while dq and a[dq[-1]] >= x: dq.pop()
dq.append(i)
if dq[0] <= i - k: dq.popleft()
if i >= k - 1: out.append(a[dq[0]])
print(out)What is printed?- A. [2, 2, -5, -5]
- B. [12, 12, 12, 11]
- C. [2, 2, -5]
- D. [2, 2, 11, -5, -5]
Correct answer: A. [2, 2, -5, -5]
The deque keeps indices of increasing values, so its front is the window minimum. The first variant pops with the wrong comparison and returns maxima; the others index the wrong range or never remove stale entries.
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
- A DP counts the minimum number of coins to pay exactly 11 with coins [2, 5], returning −1 if impossible. python INF = float('inf') coins =…
- A binary search finds the largest x with xx <= 50 using the bounds 0 and 50. python lo, hi = 0, 50 while lo < hi: mid = (lo + hi + 1) // 2…
- A routine computes the number of subarrays whose sum is divisible by 5, using the remainder of each prefix sum. python a = [3, -1, 4, -6…
- A problem asks for the minimum number of refuelling stops on a road, where the car has a fuel capacity and each station offers some fuel…
- For the problem 'choose the largest set of non-overlapping intervals', which greedy rule is correct?
- A DP over prefixes of an array computes the number of ways to split it into segments where each segment's sum is at most L. Which…