Data Structures & AlgorithmsHardFlipkart/Uber OA · placement
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 = [0, 3, 0, 2, -1, 1, 2, 3, -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. 4
- B. 5
- C. 3
- D. 2
Correct answer: C. 3
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: 3.
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
- Rotate a square matrix 90° clockwise in place by transposing and then reversing each row. What is printed? python m = [[1, 2, 3], [4, 5…
- For the binary array [0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1], replace 0 by −1 and use prefix sums with a first-occurrence map. What is the…
- Which application does NOT naturally use a stack?
- Two numbers are stored as linked lists with digits in REVERSE order (units first). What does this addition print? python def add(a, b): d…
- How many contiguous subarrays of [5, 4, 4, 3, 2, 5, 2, 2] have a sum between 7 and 11 inclusive? (All values positive: count atMost(11) −…
- KMP failure function (lps[i] = length of the longest proper prefix of p[0..i] that is also a suffix). What is printed? python def lps(p)…