Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard

Problem: Minimum number of swaps (any two positions) needed to sort an array of distinct values, by counting cycles of the permutation.

Problem: Minimum number of swaps (any two positions) needed to sort an array of distinct values, by counting cycles of the permutation.
def min_swaps(a):
    pos = sorted(range(len(a)), key=lambda i: a[i])
    seen = [False] * len(a); swaps = 0
    for i in range(len(a)):
        L = 0; j = i
        while not seen[j]: seen[j] = True; j = pos[j]; L += 1
        if L: swaps += L - 1
    return swaps
print(min_swaps([4, 3, 1, 2, 5, 7, 6]))
What is printed?
  1. A. 5
  2. B. 3
  3. C. 6
  4. D. 4

Correct answer: D. 4

Each cycle of length L needs L − 1 swaps. Here 4 → position of 4 … forms one 4-cycle among the first four values (3 swaps), 5 is fixed, and 7, 6 form a 2-cycle (1 swap): 4. Bubble-sort-style adjacent swaps would need as many as the inversions (6).

More Coding Interview Problems questions

Exams that ask this topic