Data Structures & AlgorithmsHardGATE CS · DSA
Count zero-sum contiguous subarrays with a prefix-sum frequency map. What is printed?
Count zero-sum contiguous subarrays with a prefix-sum frequency map. What is printed?
from collections import defaultdict
a = [1, -2, -1, 2, -3, 2, 0, 3, -2]
f, p, cnt = defaultdict(int), 0, 0
f[0] = 1
for x in a:
p += x; cnt += f[p]; f[p] += 1
print(cnt)- A. 1
- B. 4
- C. 6
- D. 3
Correct answer: C. 6
Prefix sums 0, 1, −1, −2, 0, −3, −1, −1, 2, 0: value 0 occurs 3 times and −1 occurs 3 times, so C(3,2) + C(3,2) = 6. Without the seed f[0] = 1 only 4 are found; pairing the zeros alone gives 3, and 1 counts just the single 0 element.
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
- Daily prices are [26, 31, 28, 30, 24, 30, 18, 37, 13]. What is the maximum profit with at most ONE buy and one later sell, and with…
- Floyd's cycle detection on a list whose last node links back into the list. What does this print (meeting value, cycle-start value, cycle…
- One Lomuto partition (pivot = LAST element; i marks the end of the 'less than pivot' region; when a[j] < pivot, increment i and swap a[i]…
- 9 people stand in a circle numbered 1 to 9. Counting starts at person 1, and every 3rd person is removed (counting continues from the next…
- A hash-map two-sum returns the first index pair (i, j), i < j, found while scanning left to right. What is printed? python def twosum(a…
- A sorted array was rotated to give [29, 47, 50, 57, 60, 61, 75, 4, 5, 8, 13]. Binary search finds the index of the minimum: while lo < hi…