Data Structures & AlgorithmsVery hardProduct Company SDE · ICPC regional
Count the non-empty subarrays of a = [3, -1, 4, -1, 5, -9, 2, 6] whose sum is divisible by 5, using prefix sums taken modulo 5.
Count the non-empty subarrays of a = [3, -1, 4, -1, 5, -9, 2, 6] whose sum is divisible by 5, using prefix sums taken modulo 5.
a=[3,-1,4,-1,5,-9,2,6]
c={0:1}; s=0; ans=0
for x in a:
s=(s+x)%5
ans+=c.get(s,0); c[s]=c.get(s,0)+1
print(ans)What is printed?- A. 5
- B. 3
- C. 1
- D. 2
Correct answer: A. 5
Equal prefix residues mod 5 mark a subarray whose sum is divisible by 5; the map must start with residue 0 for the empty prefix. Using raw prefix sums counts zero-sum subarrays instead, and checking only prefixes from index 0 misses most subarrays.
More Coding Interview Problems questions
- Items (weight, value) are (5,10), (4,7), (6,12), (3,4) and the knapsack capacity is 10. Each item may be taken at most once. Run the exact…
- Binary string s = "1101001110001011". Find the length of the longest contiguous substring that contains equally many 0s and 1s. python…
- Intervals (start, end) are compatible when one ends at or before the other starts. Run the earliest-finish greedy on the list below and…
- Coins of denominations 1, 3 and 4 are available with unlimited supply. For the amount 6, run the DP that finds the minimum number of coins…
- Array a = [1, 3, 2, 3, 1, 4, 5, 2]. Subsequences are chosen by index (positions may repeat values). Count the strictly increasing…
- Two strings are "intention" and "execution". Compute the minimum cost to turn the first into the second, where insertion and deletion cost…