Data Structures & AlgorithmsVery hardFlipkart/Uber OA · placement

For s = "cdbccdddbaddca", 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. 5 and 24
  2. B. 5 and 38
  3. C. 9 and 38
  4. D. 4 and 38

Correct answer: B. 5 and 38

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 38.

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

Exams that ask this topic