Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Return the maximum of every window of size k in a stream of readings.
Problem: Return the maximum of every window of size k in a stream of readings.
from collections import deque
def win_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(win_max([4, 2, 12, 3, 8, 1, 7], 3))What is printed?- A. [12, 12, 8, 8, 7]
- B. [4, 12, 12, 8, 8]
- C. [12, 12, 12, 8, 8]
- D. [12, 12, 12, 8, 7]
Correct answer: C. [12, 12, 12, 8, 8]
A deque keeps indices of decreasing values; the front is the window maximum and is dropped once it slides out. Windows: [4,2,12]=12, [2,12,3]=12, [12,3,8]=12, [3,8,1]=8, [8,1,7]=8. Each index is pushed and popped once, so O(n) versus O(nk) for rescanning each window.
More Coding Interview Problems questions
- Problem: For n = 10⁶ readings and window size k = 10⁵, report every window maximum. Which approach fits the limits best?
- Problem: Count how many substrings of length k in a DNA string contain exactly k distinct letters. python def countdistinct(s, k): freq, c…
- Problem: Find the length of the longest substring that can be turned into a single repeated letter by changing at most k characters…
- Problem: Return the smallest window of s that contains every character of t (with multiplicity). python from collections import Counter…
- Problem: A username is valid if it reads the same forwards and backwards after removing non-alphanumeric characters and ignoring case…
- Problem: Return True if one character can be deleted from a word to make it a palindrome (or it already is one). python def almost(s): def…