Data Structures & AlgorithmsVery hardCodeforces Div2 C · TCS NQT
A routine computes the number of subarrays whose sum is divisible by 5, using the remainder of each prefix sum.
A routine computes the number of subarrays whose sum is divisible by 5, using the remainder of each prefix sum.
a = [3, -1, 4, -6, 2, 1]
pre = [0]
for x in a: pre.append(pre[-1] + x)
cnt = {}
ans = 0
for s in pre:
r = s % 5
ans += cnt.get(r, 0)
cnt[r] = cnt.get(r, 0) + 1
print(ans)What is printed?- A. 2
- B. 6
- C. 4
- D. 3
Correct answer: D. 3
Python's % always returns a remainder in [0, 5), so equal remainders mean the difference is divisible by 5. Mapping the remainder through abs (as C/Java would with a sign-preserving %) splits equal residues into different buckets and undercounts.
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
- A problem asks for the minimum number of refuelling stops on a road, where the car has a fuel capacity and each station offers some fuel…
- For the problem 'choose the largest set of non-overlapping intervals', which greedy rule is correct?
- A DP over prefixes of an array computes the number of ways to split it into segments where each segment's sum is at most L. Which…
- Which problem is the standard application of 'binary search on the answer' where the feasibility test itself is a greedy scan?
- In bitmask DP over subsets of n items, what is the typical total time for the TSP-style recurrence dp[mask][last] with transitions to…
- Which statement about the 'house robber' DP on a line is correct?