Data Structures & AlgorithmsVery hardGATE CS · DSA

How many contiguous subarrays of [−2, 1, −3, −4, 8, 1, 4, −5, 6] have a sum divisible by 3? (Count equal prefix-sum remainders.)

  1. A. 11
  2. B. 13
  3. C. 8
  4. D. 12

Correct answer: D. 12

Two prefixes with the same remainder bound a subarray whose sum is divisible by 3, so add C(f, 2) over remainder classes (including prefix 0). Normalising negative remainders matters: in C/Java, −1 % 3 is −1, which must be mapped to 2; done right the count is 12.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic