Data Structures & AlgorithmsModerateTCS NQT · Infosys

Binary array a = [1, 0, 1, 1, 0, 0, 1, 0, 1]. How many contiguous subarrays have exactly two 1s?

  1. A. 13
  2. B. 12
  3. C. 10
  4. D. 32

Correct answer: B. 12

Prefix count of ones: count pairs of prefixes whose difference is exactly 2. Subarrays with at most two ones include the ones with fewer, which is the trap; the exact-match count uses equal-difference pairs.

More Coding Interview Problems questions

Exams that ask this topic