Data Structures & AlgorithmsHard

In the binary array [1, 0, 0, 1, 0, 1, 1, 0, 0, 0], how many contiguous subarrays contain equal numbers of 0s and 1s?

  1. A. 10
  2. B. 14
  3. C. 4
  4. D. 15

Correct answer: B. 14

Map 1 to +1 and 0 to −1; equal counts means a zero-sum subarray, which is a pair of equal prefix sums. Forgetting the prefix 0 at the start misses subarrays beginning at index 0, while counting prefixes instead of pairs gives a different number.

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

Exams that ask this topic