Data Structures & AlgorithmsHardProduct Company SDE · prefix-count OA

Problem: How many contiguous subarrays of [1, 2, 1, 2, 1, 3, 1] contain exactly 2 odd numbers?

Problem: How many contiguous subarrays of [1, 2, 1, 2, 1, 3, 1] contain exactly 2 odd numbers?
a = [1, 2, 1, 2, 1, 3, 1]
k = 2
cnt = 0
for i in range(len(a)):
    for j in range(i, len(a)):
        if sum(x % 2 for x in a[i:j + 1]) == k:
            cnt += 1
print(cnt)
What is printed?
  1. A. 19
  2. B. 16
  3. C. 7
  4. D. 6

Correct answer: C. 7

The brute force counts subarrays with exactly k = 2 odd values: 7. The linear method counts prefix-odd-count pairs differing by k, or uses atMost(2) − atMost(1). Counting 'at most 2' gives 19, 'at least 2' gives 16, and slicing a[i:j] instead of a[i:j + 1] drops the last element and gives 6.

More Coding Interview Problems questions

Exams that ask this topic