Skip to content
BytePatterns

Fewest Swaps to Sort

MediumSorting#cycle-decomposition#selection-sort~25m

Problem

Given a list of distinct integers, return the smallest number of swaps that sorts it in ascending order. One swap exchanges the values at any two positions, and the two positions do not have to be next to each other.

Examples

Input:  nums = [4, 3, 1, 2]
Output: 3
Why:    4 must go to index 3, the 2 there to index 1, the 3 there to
        index 2 and the 1 there to index 0: one loop of four values
Input:  nums = [10, 30, 20]
Output: 1
Why:    swapping 30 and 20 is enough
Input:  nums = [7]
Output: 0
Why:    edge case, a single value is already sorted

Hints

0 / 3

Stuck on the idea rather than the code? Selection Sort covers it.