Data Structures & AlgorithmsVery hard

Using AT MOST ONE swap of two elements, what is the lexicographically smallest array obtainable from 3 1 2 5 4?

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

Correct answer: B. 1 3 2 5 4

Brute force over the single swaps (including none) gives the minimum; the best swap brings the smallest value that appears later to the earliest position where it is smaller. Sorting the whole array needs more than one swap in general.

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

Exams that ask this topic