Data Structures & AlgorithmsVery hardProduct company OA
Count subarrays whose sum is divisible by 3 using prefix sums and a remainder map. The second version imitates C's % operator (sign follows the dividend). What is printed?
Count subarrays whose sum is divisible by 3 using prefix sums and a remainder map. The second version imitates C's % operator (sign follows the dividend). What is printed?
def div_count(a, k):
seen = {0: 1}; s = c = 0
for x in a:
s = (s + x) % k
c += seen.get(s, 0)
seen[s] = seen.get(s, 0) + 1
return c
def c_style(a, k):
seen = {0: 1}; s = c = 0
for x in a:
s = s + x
r = abs(s) % k * (1 if s >= 0 else -1)
c += seen.get(r, 0)
seen[r] = seen.get(r, 0) + 1
return c
a = [4, -6, 2, -3, 5, 1]
print(div_count(a, 3), c_style(a, 3))- A. 6 7
- B. 7 7
- C. 5 6
- D. 7 6
Correct answer: D. 7 6
Two prefixes with equal remainder bracket a subarray whose sum is a multiple of k. Prefix sums: 4, −2, 0, −3, 2, 3. Python's % maps them to 1, 1, 0, 0, 2, 0; with the initial 0 the classes are {0: 4, 1: 2, 2: 1} → C(4,2) + C(2,2) = 7. With C-style %, −2 gives −2 instead of 1, so the 4 and −2 prefixes land in different buckets and that pair is missed → 6. In C/C++/Java one must normalise ((s % k) + k) % k.
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
- Longest subarray with sum exactly 5 when the array contains NEGATIVE numbers: a shrink-when-too-big sliding window versus a prefix-sum map…
- Total element copies when a dynamic array is filled with 100 items under three growth rules (cost, final capacity). What is printed?…
- A 'last position ≤ x' binary search with the loop capped at 50 iterations, returning (lo, iterations). What is printed? python def…
- Packages must ship in order, one contiguous group per day; binary search on the daily capacity finds the smallest capacity that finishes…
- Minimum window of s containing every character of t WITH multiplicity, using a need-counter. What is printed? python from collections…
- Shortest subarray with sum ≥ 5 in an array WITH negative numbers: an increasing deque of prefix-sum indices versus the usual shrinking…