Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Count subarrays whose sum is divisible by k (values may be negative).
Problem: Count subarrays whose sum is divisible by k (values may be negative).
def div_k(a, k):
cnt = [0] * k
cnt[0] = 1
p = ans = 0
for x in a:
p = (p + x) % k
ans += cnt[p]
cnt[p] += 1
return ans
print(div_k([4, 5, 0, -2, -3, 1], 5))What is printed?- A. 7
- B. 6
- C. 4
- D. 13
Correct answer: A. 7
Two prefixes with the same remainder bound a divisible subarray. Python's % keeps remainders in 0..k−1, so the prefix remainders are 0 (initial), 4, 4, 4, 2, 4, 0 and pairs = C(2,2) + C(4,2) = 1 + 6 = 7. Forgetting the initial cnt[0] = 1 gives 6, counting after incrementing gives 13, and C++/Java-style truncated remainders (negative buckets) give 4 unless you write ((p % k) + k) % k.
More Coding Interview Problems questions
- Problem: For n ≤ 2 × 10⁵ integers in the range −10⁴..10⁴, count subarrays with sum exactly k. Why does a two-pointer sliding window NOT…
- Problem: A game keeps scores in a non-decreasing array. Remove duplicates in place and return the number of unique scores. python def…
- Problem: Allow each value at most twice in a sorted array (in place) and return the new length. python def keep2(a): w = 0 for x in a: if…
- Problem: Two sorted arrays must be merged into the first one, which has spare slots at the end (m real values, n values in the second)…
- Problem: In a sorted array of distinct heights, count pairs (i < j) whose sum is strictly less than a limit. python def pairsbelow(a…
- Problem: Bars of heights h[i] stand at positions i. Pick two bars that hold the most water between them (area = min height × distance)…