Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Arrays

Minimum Swaps to Sort

Medium · Arrays · Asked at Amazon, Microsoft, Samsung

All elements are distinct. In one swap you may exchange any two elements. Print the minimum number of swaps needed to sort the array in increasing order.

Input

First line: n. Second line: n space-separated integers.

Output

The minimum number of swaps.

Constraints

Find where each element belongs in the sorted order. The positions form cycles (i → where a[i] should go); a cycle of length L needs exactly L − 1 swaps. Sum over all cycles.

Example 1

Input

4
4 3 2 1

Output

2

Example 2

Input

5
1 5 4 3 2

Output

2

Hints

  1. Look at where each element must end up in sorted order.
  2. Following "element at i belongs at position j" forms cycles.
  3. A cycle of length L can be fixed with L − 1 swaps, and no fewer.

Approach

Sort a copy (with original indices) to know the target position of every element. Then walk each unvisited index i, following i → target(a[i]) until you return, counting the cycle length L. Add L − 1 for each cycle. Every swap can place at most one extra element correctly inside a cycle, which is why L − 1 is the minimum.

Complexity: O(n log n) time · O(n) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    cin >> n;
    vector<pair<long long, int>> v(n);
    for (int i = 0; i < n; i++) {
        cin >> v[i].first;
        v[i].second = i;
    }
    sort(v.begin(), v.end());
    // after sorting, position i should hold the element that was at v[i].second
    vector<bool> seen(n, false);
    long long swaps = 0;
    for (int i = 0; i < n; i++) {
        if (seen[i]) continue;
        int len = 0;
        for (int j = i; !seen[j]; j = v[j].second) {
            seen[j] = true;
            len++;
        }
        swaps += len - 1;
    }
    cout << swaps << "\n";
    return 0;
}

Python solution

import sys

data = list(map(int, sys.stdin.read().split()))
n = data[0]
a = data[1 : 1 + n]
order = sorted(range(n), key=lambda i: a[i])  # order[i] = original index of the i-th smallest
seen = [False] * n
swaps = 0
for i in range(n):
    if seen[i]:
        continue
    length, j = 0, i
    while not seen[j]:
        seen[j] = True
        j = order[j]
        length += 1
    swaps += length - 1
print(swaps)

Java solution

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        in.nextToken();
        int n = (int) in.nval;
        long[] a = new long[n];
        Integer[] order = new Integer[n];
        for (int i = 0; i < n; i++) {
            in.nextToken();
            a[i] = (long) in.nval;
            order[i] = i;
        }
        Arrays.sort(order, (x, y) -> Long.compare(a[x], a[y]));
        boolean[] seen = new boolean[n];
        long swaps = 0;
        for (int i = 0; i < n; i++) {
            if (seen[i]) continue;
            int len = 0;
            for (int j = i; !seen[j]; j = order[j]) {
                seen[j] = true;
                len++;
            }
            swaps += len - 1;
        }
        System.out.println(swaps);
    }
}

Solve Minimum Swaps to Sort online · All practice problems