Data Structures & AlgorithmsVery hard

In the 'minimum swaps to sort a permutation' problem, why is the answer n minus the number of cycles?

  1. A. Every element needs exactly one swap regardless of cycles.
  2. B. The answer is the number of inversions in the permutation.
  3. C. The answer equals the length of the longest increasing subsequence.
  4. D. Each cycle of length L can be sorted with L−1 swaps, and the total over all cycles is n minus the cycle count.

Correct answer: D. Each cycle of length L can be sorted with L−1 swaps, and the total over all cycles is n minus the cycle count.

Within a cycle of length L, L−1 swaps place every element, and the cycles are independent, so the swap counts add. Counting inversions measures a different quantity.

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

Exams that ask this topic