Data Structures & AlgorithmsVery hardProduct company OA
Shortest subarray with sum ≥ 5 in an array WITH negative numbers: an increasing deque of prefix-sum indices versus the usual shrinking window. What is printed?
Shortest subarray with sum ≥ 5 in an array WITH negative numbers: an increasing deque of prefix-sum indices versus the usual shrinking window. What is printed?
from collections import deque
def shortest(a, K):
P = [0]
for x in a: P.append(P[-1] + x)
dq, best = deque(), 10**9
for j in range(len(P)):
while dq and P[j] - P[dq[0]] >= K: best = min(best, j - dq.popleft())
while dq and P[dq[-1]] >= P[j]: dq.pop()
dq.append(j)
return best if best < 10**9 else -1
def naive_window(a, K):
lo = s = 0; best = 10**9
for hi, x in enumerate(a):
s += x
while s >= K: best = min(best, hi - lo + 1); s -= a[lo]; lo += 1
return best if best < 10**9 else -1
a = [2, -1, 2, -4, 3, 1, -2, 4]
print(shortest(a, 5), naive_window(a, 5))- A. 4 4
- B. 2 8
- C. 4 8
- D. -1 8
Correct answer: C. 4 8
With negatives, prefix sums are not monotone, so the shrinking window is wrong: it only shrinks while the sum is ≥ K and here reaches K only with the whole array → 8. The deque keeps prefix indices with increasing values: a later smaller prefix is always a better start, so larger ones are dropped from the back, and a front index is popped as soon as it yields a valid subarray (later ends could only be longer). Result: [3, 1, −2, 4] of length 4. O(n).
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- Probe-sequence coverage for open addressing: how many distinct slots can the offsets i² (quadratic) and i(i+1)/2 (triangular) reach in…
- An LRU cache of capacity 3 (OrderedDict, oldest first) processes page requests. How many misses, and what is the final order? python from…
- Minimum number of brackets to INSERT to make a string balanced, returned as (total, unmatched ')', unmatched '('). What is printed? python…
- Boyer–Moore majority vote WITHOUT the verification pass, returning (candidate, final counter). What is printed? python def vote(a): cand…
- Inversions counted during merge sort (pairs i < j with a[i] > a[j]). What is printed? python def inv(a): if len(a) <= 1: return a, 0 m =…
- One Hoare partition with the FIRST element (6) as pivot. What is printed (array after the partition, returned index)? python def hoare(a)…