Data Structures & AlgorithmsHardTCS Digital · Infosys SP
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, -3, 2, -3, -3, 3, -3, 2, 1]
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. 6
- B. 7
- C. 5
- D. 4
Correct answer: C. 5
Each earlier prefix equal to the current one bounds a zero-sum subarray; seeding f[0] = 1 counts subarrays that start at index 0. Count: 5.
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
- Bubble sort (ascending; each pass compares adjacent pairs left to right and swaps if out of order) is applied to [5, 42, 29, 4, 41, 8, 53…
- Stock prices over 8 days are [27, 32, 42, 42, 35, 66, 59, 31]. The span of day i is the number of consecutive days ending at day i…
- Assertion (A): Binary search runs in O(log n) time on a sorted singly linked list. Reason (R): Binary search halves the search range in…
- Two strings are isomorphic if characters can be replaced one-to-one to turn one into the other. Version A checks both directions; version…
- A monotonic deque reports the maximum of every window of size 3 in [0, 13, 9, 1, 2, 18, −1, −3, 17]. What is the SUM of all reported…
- An array of 8 zeros (indices 0–7) receives range updates with a difference array (diff[l] += v, diff[r + 1] −= v, then prefix-sum): add 5…