Data Structures & AlgorithmsVery hard

In "xaybzaxxbab", what is the length of the shortest contiguous substring that contains the letter 'a' followed later by the letter 'b' (the two need not be adjacent)?

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

Correct answer: C. 2

For each 'a' take the nearest later 'b'; the shortest such span is the minimum of these distances plus one. A two-pointer or stack sweep finds the same minimum in linear time.

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

Exams that ask this topic