Data Structures & AlgorithmsHardGATE CS · TCS NQT

How many substrings of abbaba contain an equal number of letters a and b (substrings of length at least 2)?

  1. A. 8
  2. B. 9
  3. C. 11
  4. D. 7

Correct answer: D. 7

Map a to +1 and b to -1; a substring is balanced when its prefix sums match. Counting by prefix-sum equality is cleaner than enumerating substrings.

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

Exams that ask this topic