Data Structures & AlgorithmsHardProduct Company SDE · Amazon-style OA
Problem: Find the maximum of every window of size 3 in the array below, printing the list of window maxima.
Problem: Find the maximum of every window of size 3 in the array below, printing the list of window maxima.
from collections import deque
def sliding_max(a, k):
dq, out = deque(), []
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]])
return out
print(sliding_max([1, 3, -1, -3, 5, 3, 6, 7], 3))What is printed?- A. [3, 3, 5, 3, 6, 7]
- B. [1, 3, 3, 5, 5, 6]
- C. [3, 3, 5, 5, 5, 7]
- D. [3, 3, 5, 5, 6, 7]
Correct answer: D. [3, 3, 5, 5, 6, 7]
The monotone deque keeps indices with decreasing values, so each window's front is its maximum. The six windows give maxima 3, 3, 5, 5, 6, 7.
More Coding Interview Problems questions
- Problem: Compute the Z-array (z[i] = length of the longest common prefix of s and s[i:], with z[0] set to 0) for s = 'aabxaab'. python def…
- Problem: Count the palindromic substrings of 'abacaba' (every occurrence counts, so single characters count too). python def count(s)…
- Problem: A directed graph with V vertices is relaxed with Bellman-Ford. After V - 1 full rounds of relaxing all edges, one more round…
- Problem: A Fenwick tree of size 8 receives point adds (1,+5), (3,+2), (5,+7), (8,+1) with the usual add and prefix-query code, then prints…
- Problem: You want the maximum number of non-overlapping intervals. Which greedy rule is provably optimal?
- Problem: Count subarrays whose XOR is zero, for a = [1, 2, 3, 0, 3, 3]. python from collections import Counter def cnt(a): seen =…