Problem · Array
Minimum Swaps to Sort an Array
Learn this problemProblem statement
Given an array values of distinct integers, return the minimum number of swaps of any two positions needed to arrange the array in strictly increasing order.
Function
minimumSwaps(values: int[]) → intExamples
Example 1
values = [4,3,1,2]return = 3One optimal sequence swaps the values at positions 0 and 2, then positions 1 and 3, then positions 2 and 3, producing [1,2,3,4].
Example 2
values = [1,5,4,3,2]return = 2Swap 5 with 2, then swap 4 with 3.
Constraints
1 ≤ values.length ≤ 2 × 10^5-10^9 ≤ values[i] ≤ 10^9- All values are distinct.