Data Structures & AlgorithmsModerate

In the array [1, 2, 1, 3, 2, 1, 4, 5], how many contiguous subarrays contain exactly 2 odd numbers?

  1. A. 24
  2. B. 7
  3. C. 9
  4. D. 10

Correct answer: C. 9

Exactly k equals at-most-k minus at-most-(k−1), which is the standard difference of two sliding-window counts. Using at-most-k alone includes subarrays with fewer odd numbers, and the difference (k+1) minus k counts exactly k+1 odd numbers.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic