Data Structures & AlgorithmsVery hardProduct company OA

What is the minimum number of swaps (of any two elements) needed to sort the permutation [4, 3, 1, 2, 6, 5] into ascending order?

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

Correct answer: A. 4

Decompose into cycles of 'value v belongs at position v': positions 1 → 4 → 2 → 3 → 1 form a 4-cycle (needs 3 swaps) and 5 ↔ 6 is a 2-cycle (1 swap). Minimum = n − (number of cycles) = 6 − 2 = 4. Adjacent-swap counting (inversions) gives a larger number; '3' sees only the long cycle.

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

Exams that ask this topic