Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: A traffic monitor reports, for every window of k consecutive minutes, the busiest minute's count, and the dashboard shows the SUM of those window maxima.
Problem: A traffic monitor reports, for every window of k consecutive minutes, the busiest minute's count, and the dashboard shows the SUM of those window maxima.
from collections import deque
def f(a, k):
dq, s = deque(), 0
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:
s += a[dq[0]]
return s
print(f([4, 2, 12, 3, 8, 1, 7], 3))What is printed?- A. 52
- B. 48
- C. 44
- D. 56
Correct answer: A. 52
The deque keeps indices of a decreasing run, so its front is the window maximum. The five windows have maxima 12, 12, 12, 8, 8, giving 52. 48 comes from wrongly taking 8 for the third window [12, 3, 8].
More Coding Interview Problems questions
- Problem: Find the maximum sum of a non-empty subarray of a CIRCULAR array (a subarray may wrap from the end to the start). python def…
- Problem: Install c routers at some of the given highway mile-markers so that the smallest distance between any two routers is as LARGE as…
- A divide-and-conquer routine satisfies T(n) = 4T(n/2) + n² log n. What is its running time?
- Edge case: A helper collects items into a list using a default argument. python def collect(x, out=[]): out.append(x) return out a =…
- Problem: n servers are joined by cables one at a time. Count the connected groups at the end and how many cables were redundant (joined…
- Problem: Task IDs 0..5 with dependencies u → v (u before v). The scheduler always runs the SMALLEST available ID next. python import heapq…