Data Structures & AlgorithmsVery hardGATE CS · DSA

For the binary array [0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1], replace 0 by −1 and use prefix sums with a first-occurrence map. What is the length of the longest subarray with equal numbers of 0s and 1s, and how many such subarrays exist?

  1. A. 8 and 19
  2. B. 8 and 21
  3. C. 8 and 18
  4. D. 6 and 19

Correct answer: A. 8 and 19

Equal prefix sums (after 0 → −1) bound a balanced subarray; the longest uses each sum's first occurrence (8), and the count is Σ C(f, 2) over prefix-sum frequencies (19). 2·min(#0, #1) is only an upper bound.

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

Exams that ask this topic