Data Structures & AlgorithmsHardProduct company OA

Problem: Count the contiguous subarrays with an ODD sum using prefix-sum parity counts.

Problem: Count the contiguous subarrays with an ODD sum using prefix-sum parity counts.
def odd_sum_subarrays(a):
    even, odd, run, res = 1, 0, 0, 0
    for x in a:
        run += x
        if run % 2:
            res += even; odd += 1
        else:
            res += odd; even += 1
    return res
print(odd_sum_subarrays([7, 2, 9, 4]), odd_sum_subarrays([8, 8]), odd_sum_subarrays([1, 1, 1, 1, 1]))
What is printed?
  1. A. 6 0 9
  2. B. 6 1 9
  3. C. 4 0 9
  4. D. 6 0 6

Correct answer: A. 6 0 9

A subarray (i, j] has an odd sum exactly when prefix[j] and prefix[i] have different parity, so pair each odd prefix with earlier even prefixes (the empty prefix counts as even – hence even = 1) and vice versa. [7, 2, 9, 4]: prefixes 7, 9, 18, 22 → 1 + 1 + 2 + 2 = 6 of the 10 subarrays. Five 1s: prefixes 1..5 → 1 + 1 + 2 + 2 + 3 = 9. Starting even at 0 forgets subarrays that begin at index 0. O(n).

More Coding Interview Problems questions

Exams that ask this topic