Data Structures & AlgorithmsHard

What is the length of the longest contiguous subarray of 1 6 2 7 3 5 4 8 1 9 that contains equally many values ≥ 5 and values < 5?

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

Correct answer: D. 10

Map ≥ 5 to +1 and < 5 to −1; the whole array has five of each, so its sum is 0 and the answer is 10. Stopping at the balanced prefix of length 8 misses the last two, using > 5 instead of ≥ 5 gives 4, and 25 counts the balanced subarrays instead of measuring the longest.

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

Exams that ask this topic