Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Find the number of 'nice' subarrays containing exactly k odd numbers using prefix counts.

Problem: Find the number of 'nice' subarrays containing exactly k odd numbers using prefix counts.
def nice(a, k):
    cnt = {0: 1}; odd = res = 0
    for x in a:
        odd += x & 1
        res += cnt.get(odd - k, 0)
        cnt[odd] = cnt.get(odd, 0) + 1
    return res
print(nice([2, 2, 2, 1, 2, 2, 1, 2, 2, 2], 2), nice([1, 1, 2, 1, 1], 3))
What is printed?
  1. A. 12 2
  2. B. 16 3
  3. C. 9 2
  4. D. 16 2

Correct answer: D. 16 2

Map each element to 1 if odd and count subarrays with sum k – the same prefix-sum trick. In the first array, the block between the two odd numbers can extend 4 positions to the left and 4 to the right: 4 × 4 = 16. Second: [1,1,2,1] and [1,2,1,1]. O(n).

More Coding Interview Problems questions

Exams that ask this topic