Data Structures & AlgorithmsVery hardHCLTech · Wipro pattern

Using a sliding window (shrink from the left whenever more than k distinct characters are in the window), what is the length of the longest substring of "BDCDBDADB" containing at most k = 2 distinct characters?

  1. A. 6
  2. B. 3
  3. C. 2
  4. D. 1

Correct answer: B. 3

Sliding the window right and shrinking from the left whenever the distinct-character count exceeds k = 2 gives a longest valid window of length 3. Using k = 1 would give 1, and using k = 3 would give 6 — off-by-one errors on the distinct-count bound.

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

Exams that ask this topic