Data Structures & AlgorithmsModerateGATE CS · ICPC regional

How many substrings of the string aabbaabb have an equal number of letters a and b?

  1. A. 11
  2. B. 12
  3. C. 14
  4. D. 10

Correct answer: D. 10

Map a to +1 and b to -1; a substring is balanced when two prefix sums are equal. Counting prefix-sum repeats finds all balanced substrings in O(n) with a hash map.

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

Exams that ask this topic