Skip to problem
←

Minimum Swaps to Sort an Array

Hard 0 attempts

You're given an array of N distinct values. Using swaps that exchange any two elements, determine the fewest swaps needed to arrange the array in ascending order.

One swap can exchange any two positions, even if they are far apart. Return the count, not the sorted array or the swap sequence. An already sorted array needs 0 swaps.

For [4,3,2,1], swap 4 with 1, then 3 with 2, giving [1,2,3,4] in two swaps. This is not the adjacent-swap count.

Function contract

Implement minSwaps(arr). Receive a nonempty array of distinct positive integers.

Output: Return the minimum number of swaps between arbitrary pairs of indices required to sort the array in ascending order.

Example 1

Input
arr = [4,3,2,1]
Output
2

Example 2

Input
arr = [1,2,3]
Output
0
Constraints
  • 1 <= arr.length <= 10^5
  • 1 <= arr[i] <= 10^6
  • All values are distinct.

Cycle Detection

Sorting a copy identifies the unique target position of every value. Map values to their original indices, then follow the resulting permutation cycles. A cycle of length L needs exactly L - 1 swaps: each swap can increase the number of resolved cycles by at most one, and repeatedly placing one cycle element achieves that bound. Sum the costs of disjoint cycles; fixed points cost zero. The distinct-value constraint makes the position mapping unambiguous.

javascript
function minSwaps(arr) {
  const sorted = [...arr].sort((a,b)=>a-b);
  const idx = new Map(); arr.forEach((v,i)=>idx.set(v,i));
  const visited = Array(arr.length).fill(false);
  let swaps = 0;
  for (let i = 0; i < arr.length; i++) {
    if (visited[i] || arr[i]===sorted[i]) continue;
    let cycleLen = 0, j = i;
    while (!visited[j]) { visited[j]=true; j=idx.get(sorted[j]); cycleLen++; }
    swaps += cycleLen - 1;
  }
  return swaps;
}

Time: O(n log n) | Space: O(n)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript