Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Longest subarray whose max − min ≤ limit, using two monotonic deques.
Problem: Longest subarray whose max − min ≤ limit, using two monotonic deques.
from collections import deque
def longest(a, lim):
mx, mn, l, best = deque(), deque(), 0, 0
for r, x in enumerate(a):
while mx and a[mx[-1]] <= x: mx.pop()
while mn and a[mn[-1]] >= x: mn.pop()
mx.append(r); mn.append(r)
while a[mx[0]] - a[mn[0]] > lim:
l += 1
if mx[0] < l: mx.popleft()
if mn[0] < l: mn.popleft()
best = max(best, r - l + 1)
return best
print(longest([4, 8, 5, 1, 7, 9, 6], 3))What is printed?- A. 3
- B. 2
- C. 4
- D. 5
Correct answer: A. 3
The windows [8, 5], [7, 9, 6] and so on are checked; [7, 9, 6] has max − min = 3, length 3, and no window of length 4 stays within 3 (e.g. [1, 7, 9, 6] spans 8). The deques give O(n) instead of re-scanning each window.
More Coding Interview Problems questions
- Problem: Count subarrays whose maximum lies in [L, R] in one pass. python def count(a, L, R): lastbad = lastok = -1; res = 0 for i, x in…
- Problem: Shortest path (in steps) from the top-left to the bottom-right cell of a grid where 1 is a wall, if you may remove at most k…
- Problem: A lock has 4 wheels of digits 0–9; one move turns one wheel by ±1 (wrapping 9↔0). Starting at '0000', find the fewest moves to…
- Problem: Water level t floods every cell of height ≤ t. Find the smallest t at which you can swim from the top-left to the bottom-right…
- Problem: Connect all points with minimum total Manhattan-distance wiring (dense-graph Prim in O(n²)). python def mst(p): n = len(p); dist…
- Problem: Courses with prerequisites (u → v means u before v); any number of courses can be taken per semester. Find the minimum number of…