Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Find the minimum number of swaps to sort an array of distinct values.

Problem: Find the minimum number of swaps to sort an array of distinct values.
def min_swaps(a):
    order = sorted(range(len(a)), key=lambda i: a[i])
    seen = [False] * len(a); swaps = 0
    for i in range(len(a)):
        if seen[i] or order[i] == i: continue
        j, cyc = i, 0
        while not seen[j]:
            seen[j] = True; j = order[j]; cyc += 1
        swaps += cyc - 1
    return swaps
print(min_swaps([4, 3, 2, 1]), min_swaps([1, 5, 4, 3, 2]), min_swaps([2, 3, 4, 1, 5]))
What is printed?
  1. A. 2 2 3
  2. B. 3 2 3
  3. C. 2 3 3
  4. D. 2 2 4

Correct answer: A. 2 2 3

Map each position to where its value belongs; the permutation splits into cycles, and a cycle of length c needs c − 1 swaps. [4, 3, 2, 1] has two 2-cycles → 2. [2, 3, 4, 1, 5] has one 4-cycle → 3. Counting inversions (6 for the first) gives adjacent-swap counts, not arbitrary swaps. O(n log n).

More Coding Interview Problems questions

Exams that ask this topic