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))- A. 5 7
- B. 0 4
- C. 0 7
- 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).
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
- Total element copies when a dynamic array is filled with 100 items under three growth rules (cost, final capacity). What is printed?…
- A 'last position ≤ x' binary search with the loop capped at 50 iterations, returning (lo, iterations). What is printed? python def…
- Packages must ship in order, one contiguous group per day; binary search on the daily capacity finds the smallest capacity that finishes…
- Minimum window of s containing every character of t WITH multiplicity, using a need-counter. What is printed? python from collections…
- Shortest subarray with sum ≥ 5 in an array WITH negative numbers: an increasing deque of prefix-sum indices versus the usual shrinking…
- Probe-sequence coverage for open addressing: how many distinct slots can the offsets i² (quadratic) and i(i+1)/2 (triangular) reach in…