ProgrammingVery hardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode? (mod keeps the sign of the dividend (as in C); arrays are indexed from 0)

What will be the output of the following pseudocode? (mod keeps the sign of the dividend (as in C); arrays are indexed from 0)
Integer a[6] = {4, 5, 0, -2, -3, 1}, k = 5
Integer cnt[5] = {1, 0, 0, 0, 0}
Integer s = 0, r, ans = 0
for (each i from 0 to 5)
    s = s + a[i]
    r = ((s mod k) + k) mod k
    ans = ans + cnt[r]
    cnt[r] = cnt[r] + 1
end for
Print ans
  1. A. 5
  2. B. 6
  3. C. 4
  4. D. 7

Correct answer: D. 7

Two prefix sums with the same remainder mod 5 enclose a subarray divisible by 5. Prefix sums 0, 4, 9, 9, 7, 4, 5 have remainders 0, 4, 4, 4, 2, 4, 0: remainder 4 appears 4 times (C(4, 2) = 6 pairs) and remainder 0 twice (1 pair). ans = 7.

More Pseudocode and Code Tracing questions

Exams that ask this topic