ProgrammingHardTCS NQT · Accenture

For the array a = [1, 2, 3, 4, 5, 6], the procedure below counts the contiguous subarrays of length 3 whose sum is divisible by 3. What is printed?

For the array a = [1, 2, 3, 4, 5, 6], the procedure below counts the contiguous subarrays of length 3 whose sum is divisible by 3. What is printed?
count = 0
for i = 0 to n - 3
    if (a[i] + a[i+1] + a[i+2]) mod 3 == 0 then count = count + 1
end for
Print count
  1. A. 0
  2. B. 4
  3. C. 2
  4. D. 6

Correct answer: B. 4

The window sums are 6, 9, 12 and 15, all divisible by 3, so the count is 4. Counting the windows that are not divisible gives 0, using pairs gives a different count, and wrapping around the array adds windows.

More Pseudocode and Code Tracing questions

Exams that ask this topic