Data Structures & AlgorithmsVery hardProduct Company SDE · ICPC regional

The permutation p = [4, 3, 1, 7, 6, 2, 5] of 1..7 must be sorted by swaps of any two elements. What is the minimum number of swaps? Compute it from the cycle decomposition by running the code.

The permutation p = [4, 3, 1, 7, 6, 2, 5] of 1..7 must be sorted by swaps of any two elements. What is the minimum number of swaps? Compute it from the cycle decomposition by running the code.
p=[4,3,1,7,6,2,5]
seen=[0]*8; c=0
for i in range(1,8):
    if not seen[i]:
        c+=1; j=i
        while not seen[j]: seen[j]=1; j=p[j-1]
print(7-c)
What is printed?
  1. A. 7
  2. B. 1
  3. C. 6
  4. D. 10

Correct answer: C. 6

The minimum swaps equal n minus the number of cycles, so with this single 7-cycle the answer is 6 and not the cycle count. Counting misplaced elements counts positions rather than cycles, and counting inversions measures disorder rather than cycle structure.

More Coding Interview Problems questions

Exams that ask this topic