Data Structures & AlgorithmsHardProduct Company SDE · prefix-sum OA
Problem: Count subarrays whose sum is divisible by k=5 for a = [4, 5, 0, -2, -3, 1].
Problem: Count subarrays whose sum is divisible by k=5 for a = [4, 5, 0, -2, -3, 1].
from collections import Counter
def f(a, k):
c = Counter({0: 1})
s = 0
ans = 0
for x in a:
s = (s + x) % k
ans += c[s]
c[s] += 1
return ans
print(f([4, 5, 0, -2, -3, 1], 5))What is printed?- A. 7
- B. 4
- C. 9
- D. 11
Correct answer: A. 7
Subarrays with equal prefix remainders have sums divisible by k. Python's % gives non-negative remainders for negative numbers here, which is why the code is correct.
More Coding Interview Problems questions
- Problem: Kadane's algorithm is started with best = 0 and a running sum initialised to 0, then applied to an array where every number is…
- Problem: You binary search the answer x for 'the minimum possible largest sum when an array is split into k contiguous parts'. Which…
- Problem: What is the time complexity of this loop in terms of n? python for i in range(1, n + 1): for j in range(i, n + 1, i): work()
- Problem: Count right/down paths from the top-left to the bottom-right of the 3x3 grid below, where '#' is blocked. The code returns the…
- Problem: What does the following print? python def add(x, bucket=[]): bucket.append(x) return bucket add(1) add(2) print(add(3))
- Problem: What does the following print for the array [7, 10, 4, 3, 20, 15] with k = 3? python import heapq def kth(a, k): h = [] for x in…