Data Structures & AlgorithmsHardCodeforces Div2 C · permutations

Problem: What is the minimum number of swaps needed to sort the permutation [4, 3, 2, 1] (values 1..4 each once)? Use the cycle decomposition code below.

Problem: What is the minimum number of swaps needed to sort the permutation [4, 3, 2, 1] (values 1..4 each once)? Use the cycle decomposition code below.
p = [3, 2, 1, 0]
seen = [False] * len(p)
swaps = 0
for i in range(len(p)):
    if not seen[i]:
        j = i
        size = 0
        while not seen[j]:
            seen[j] = True
            j = p[j]
            size += 1
        swaps += size - 1
print(swaps)
What is printed?
  1. A. 3
  2. B. 4
  3. C. 1
  4. D. 2

Correct answer: D. 2

The permutation has two 2-cycles (0 with 3 and 1 with 2), and each cycle of size s needs s - 1 swaps, giving 2. Counting the inversions (6) answers a different question.

More Coding Interview Problems questions

Exams that ask this topic