Data Structures & AlgorithmsVery hard

In the 'shortest window with a then b in order' problem, why does taking the nearest later 'b' for each 'a' suffice?

  1. A. The nearest 'b' is always the first character of the string.
  2. B. Any later 'b' is at least as far as the nearest one, so the nearest later 'b' gives the shortest span for that 'a'.
  3. C. Shortest spans are always between adjacent letters.
  4. D. Only the last 'a' needs to be considered.

Correct answer: B. Any later 'b' is at least as far as the nearest one, so the nearest later 'b' gives the shortest span for that 'a'.

For a fixed starting 'a', the span grows with the position of the chosen 'b', so the nearest one is optimal. Minimizing over all 'a' then gives the global shortest span.

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

Exams that ask this topic