ProgrammingVery hardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer a[5] = {1, 2, 3, 4, 5}
Integer odd = 0, even = 1, s = 0, ans = 0     // counts of prefix sums by parity
for (each i from 0 to 4)
    s = s + a[i]
    if (s mod 2 == 1)
        ans = ans + even
        odd = odd + 1
    else
        ans = ans + odd
        even = even + 1
    end if
end for
Print ans
  1. A. 15
  2. B. 9
  3. C. 6
  4. D. 10

Correct answer: B. 9

A subarray has an odd sum when its two bounding prefix sums have different parity. Prefix sums 0, 1, 3, 6, 10, 15 have parities E, O, O, E, E, O: 3 odd and 3 even, so 3 × 3 = 9 subarrays have an odd sum.

More Pseudocode and Code Tracing questions

Exams that ask this topic