Data Structures & AlgorithmsHard
When counting subarrays with sum divisible by m, why does the prefix-remainder method count pairs of equal remainders?
- A. Equal prefix sums are always adjacent.
- B. The remainder of a prefix sum is always zero.
- C. Two prefix sums with the same remainder mod m differ by a multiple of m, so the subarray between them has sum divisible by m.
- D. Only the largest prefix remainder matters.
Correct answer: C. Two prefix sums with the same remainder mod m differ by a multiple of m, so the subarray between them has sum divisible by m.
If P_j ≡ P_i (mod m), then the subarray sum P_j − P_i is divisible by m. Counting equal-residue pairs (plus the seeded zero residue) counts every qualifying subarray once.
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
- To count ordered pairs (i, j), i ≠ j, with A[i] + A[j] ≡ 0 (mod 5), which correction turns an unordered-pair count into the ordered one?
- When counting subarrays, why do two blocks with identical values but different positions count as two different subarrays?
- In the 'shortest window with a then b in order' problem, why does taking the nearest later 'b' for each 'a' suffice?
- Why is the maximum product of three values sometimes achieved by two large negatives and one large positive?
- For a binary string with no three equal consecutive bits, why is a run-length description convenient for counting?
- Why does the sliding-window approach fail to find the shortest subarray with sum divisible by m when values are NEGATIVE?