Data Structures & AlgorithmsVery hardProduct company OA
Problem: Count contiguous subarrays whose max − min ≤ k, using two monotonic deques and a shrinking left edge.
Problem: Count contiguous subarrays whose max − min ≤ k, using two monotonic deques and a shrinking left edge.
from collections import deque
def count(a, k):
mx, mn, lo, c = deque(), deque(), 0, 0
for hi, x in enumerate(a):
while mx and a[mx[-1]] <= x: mx.pop()
while mn and a[mn[-1]] >= x: mn.pop()
mx.append(hi); mn.append(hi)
while a[mx[0]] - a[mn[0]] > k:
lo += 1
if mx[0] < lo: mx.popleft()
if mn[0] < lo: mn.popleft()
c += hi - lo + 1
return c
print(count([4, 2, 2, 5, 3, 6, 1], 2), count([1, 1, 1], 0))What is printed?- A. 9 6
- B. 11 6
- C. 11 3
- D. 13 6
Correct answer: B. 11 6
For each right end the window [lo, hi] is the longest valid one ending there (shrinking only helps, so lo never moves back) and contributes hi − lo + 1 subarrays. The max-deque keeps decreasing values and the min-deque increasing values, so both extremes are read in O(1); every index enters and leaves each deque once → O(n). For [4, 2, 2, 5, 3, 6, 1] with k = 2 the total is 11, which brute force confirms; for three equal values every one of the 6 subarrays qualifies.
More Coding Interview Problems questions
- Problem: Return the k-th smallest absolute difference among all pairs of readings (n up to 10⁵, so the n² pairs cannot be listed). Binary…
- Problem: Tasks of given lengths must be packed into work sessions of at most T = 8 hours; a task cannot be split. Exact bitmask DP (state…
- Problem: Paint a 3 × n wall: each cell gets one of 3 colours and side-adjacent cells must differ. Count valid colourings by DP over row…
- Problem: Each event (start day, end day) can be attended on any ONE day in its range, and you can attend at most one event per day…
- Problem: Roads are closed one by one; after each closure report the number of connected components. Process offline: start from the graph…
- Problem: Shortest route where exactly one road may be used at half price (one coupon). Dijkstra on states (junction, coupon used?). python…