Data Structures & AlgorithmsVery hardProduct company OA

Longest subarray with sum exactly 5 when the array contains NEGATIVE numbers: a shrink-when-too-big sliding window versus a prefix-sum map that stores the first index of each prefix. What is printed?

Longest subarray with sum exactly 5 when the array contains NEGATIVE numbers: a shrink-when-too-big sliding window versus a prefix-sum map that stores the first index of each prefix. What is printed?
def window(a, k):
    lo = s = best = 0
    for hi, x in enumerate(a):
        s += x
        while s > k and lo <= hi: s -= a[lo]; lo += 1
        if s == k: best = max(best, hi - lo + 1)
    return best
def prefix_map(a, k):
    first = {0: -1}; s = best = 0
    for i, x in enumerate(a):
        s += x
        if s - k in first: best = max(best, i - first[s - k])
        first.setdefault(s, i)
    return best
a = [3, 4, -7, 1, 3, 3, -2, 1]
print(window(a, 5), prefix_map(a, 5))
  1. A. 5 7
  2. B. 0 4
  3. C. 0 7
  4. D. 4 7

Correct answer: C. 0 7

The sliding window assumes that extending the window never decreases the sum, which is false with negatives: here it shrinks past useful starts and never sees a sum of exactly 5 → 0. The prefix map looks for an earlier prefix equal to current − 5; storing only the FIRST occurrence maximises the length. Prefixes 0,3,7,0,1,4,7,5,6: at index 6 (prefix 5) the earliest prefix 0 is at −1 → length 7 (3+4−7+1+3+3−2 = 5). O(n).

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

Exams that ask this topic