Data Structures & AlgorithmsVery hardCodeforces Div2 B-D · ICPC regional

A binary array of length 10^6 needs its longest contiguous subarray with equally many 0s and 1s. Which approach is correct and linear?

  1. A. Map 0 to -1, keep prefix sums, and store the first index of each prefix value in a hashmap; the longest gap between equal prefixes is the answer
  2. B. Two pointers that always expand the window, because the balance is monotone
  3. C. Sorting the array, then taking the longest run of equal values
  4. D. Binary search on the window length with a fixed-size check of counts only at the endpoints

Correct answer: A. Map 0 to -1, keep prefix sums, and store the first index of each prefix value in a hashmap; the longest gap between equal prefixes is the answer

Rewriting 0 as -1 turns the balance condition into a zero-sum subarray, which prefix sums with first occurrences solve in one pass. The balance is not monotone, so two pointers fail.

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

Exams that ask this topic