Data Structures & AlgorithmsHardGATE CS · Codeforces Div2 C

What is the minimum number of swaps of two (not necessarily adjacent) elements needed to sort the array [4, 3, 2, 1, 6, 5] into increasing order? Elements are distinct.

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

Correct answer: D. 3

Map each element to its sorted position and count the cycles of that permutation; the answer is n minus the number of cycles. Counting inversions counts adjacent-swap steps, which is a different (larger) number.

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

Exams that ask this topic