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))
  1. A. 4 4
  2. B. 2 8
  3. C. 4 8
  4. 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).

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic