Data Structures & AlgorithmsVery hardProduct company OA

What is the length of the longest contiguous subarray of [0, 1, 1, 0, 1, 1, 1, 0, 0, 0] with an equal number of 0s and 1s? (Map 0 to −1 and look for repeated prefix sums.)

  1. A. 8
  2. B. 6
  3. C. 4
  4. D. 10

Correct answer: D. 10

With 0 → −1 the prefix sums are −1, 0, 1, 0, 1, 2, 3, 2, 1, 0. The sum 0 first occurs at the start (index −1) and last at index 9, so the WHOLE array has five 0s and five 1s: length 10. Storing the LAST occurrence of each sum instead of the first finds only shorter windows.

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

Exams that ask this topic