Data Structures & AlgorithmsHardProduct Company SDE · CP practice

Problem: How many subarrays of [2, 4, 1, 3, 6, 5] have an even sum? Run the code.

Problem: How many subarrays of [2, 4, 1, 3, 6, 5] have an even sum? Run the code.
a = [2, 4, 1, 3, 6, 5]
print(sum(1 for i in range(len(a)) for j in range(i + 1, len(a) + 1) if sum(a[i:j]) % 2 == 0))
What is printed?
  1. A. 11
  2. B. 10
  3. C. 12
  4. D. 21

Correct answer: A. 11

Prefix parities 0, 0, 0, 1, 0, 0, 1 hold five 0s and two 1s, so C(5,2) + C(2,2) = 11 even-sum subarrays. Odd sums number 10, matching only the endpoint parities gives 12, and 21 counts all subarrays.

More Coding Interview Problems questions

Exams that ask this topic