Data Structures & AlgorithmsVery hardTCS Digital · Infosys SP

For s = "bcadbdaccdddbd", what is the length of the longest substring with at most 2 distinct characters, and how many substrings (by position) have at most 2 distinct characters?

  1. A. 7 and 40
  2. B. 5 and 26
  3. C. 5 and 40
  4. D. 4 and 40

Correct answer: C. 5 and 40

Shrink from the left whenever a third letter enters. The longest window is 5. For counting, every right end r contributes (r − left + 1) valid substrings; summing gives 40.

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

Exams that ask this topic