Data Structures & AlgorithmsVery hardProduct company OA
A monotonic deque reports the maximum of every window of 3 readings and counts deque removals. What is printed?
A monotonic deque reports the maximum of every window of 3 readings and counts deque removals. What is printed?
from collections import deque
def win_max(a, k):
dq, out, pops = deque(), [], 0
for i, x in enumerate(a):
while dq and a[dq[-1]] <= x: dq.pop(); pops += 1
dq.append(i)
if dq[0] <= i - k: dq.popleft(); pops += 1
if i >= k - 1: out.append(a[dq[0]])
return out, pops
print(*win_max([5, 1, 3, 2, 6, 2, 2, 4, 1], 3))- A. [5, 3, 6, 6, 6, 4, 4] 9
- B. [5, 3, 6, 6, 6, 4, 4] 7
- C. [5, 3, 6, 6, 6, 6, 4] 7
- D. [5, 5, 6, 6, 6, 4, 4] 7
Correct answer: B. [5, 3, 6, 6, 6, 4, 4] 7
The deque holds indices with strictly decreasing values; a new reading evicts every smaller-or-equal one from the back, and the front is dropped once it falls out of the window. Windows: [5,1,3]→5, [1,3,2]→3, [3,2,6]→6, [2,6,2]→6, [6,2,2]→6, [2,2,4]→4, [2,4,1]→4. Each index enters once and leaves at most once, so total removals ≤ n; here 7 (5 back pops + 2 front expiries), which is why the whole pass is O(n) even though the inner while looks quadratic.
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
- atmost(s, k) counts substrings with at most k distinct letters using a sliding window and a frequency map. What is printed? python def…
- A KMP prefix (failure) table and an overlapping-occurrence counter. What is printed? python def prefix(p): pi = [0] len(p) for i in…
- Z-array (z[i] = length of the longest common prefix of s and s[i:]). What is printed? python def z(s): n = len(s); z = [0] n; l = r = 0…
- Rabin–Karp over digits with base 10 and a deliberately tiny modulus 7. It returns (true matches, spurious hash hits). What is printed?…
- Open addressing with linear probing (size 7, h(k) = k mod 7). Deletion leaves a tombstone 'X'; insert reuses the first tombstone; find…
- Largest rectangle under a histogram using a stack of (start index, height). What is printed? python def rect(h): st, best = [], 0 for i, x…