Data Structures & AlgorithmsHardProduct company OA · Amazon/Microsoft-style OA
What does this Python program print?
What does this Python program print?
a = [2, -2, 3, -3, 1, 1]
p = {0: 1}; s = 0; ans = 0
for x in a:
s += x
ans += p.get(s, 0)
p[s] = p.get(s, 0) + 1
print(ans)- A. 4
- B. 2
- C. 3
- D. 5
Correct answer: A. 4
The map counts earlier prefix sums equal to the current one, so each hit is a zero-sum subarray. Starting the map without the empty prefix 0 drops subarrays beginning at index 0; the program prints the true count of zero-sum subarrays.
More Coding Interview Problems questions
- What does this program print? python from collections import Counter a = [3, 1, 2, 3, 1, 2, 3] c = Counter(a) pairs = sum(v (v - 1) // 2…
- What does this program print? python a = [6, 3, 8, 1] mx = [0] len(a) mx[-1] = a[-1] for i in range(len(a) - 2, -1, -1): mx[i] = max(a[i]…
- Array a = [7, -3, 2, 5, -8, 4, 1, -1]. How many contiguous subarrays have a sum divisible by 3? (Zero is divisible by 3.)
- Sorted list [3, 6, 9, 12, 15, 18, 21]. How many index triples i < j < k satisfy vals[i] + vals[j] = vals[k]?
- How many contiguous subarrays of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] sum to exactly 15?
- Array a = [9, 4, 7, 1, 8, 2, 6, 3]. How many index pairs i < j have |a[i] - a[j]| >= 5?