minimum no. of swaps required to sort the array
Pattern: Cyclic sort
Each value has a home index in the sorted order. Following value to home splits the array into cycles, and a cycle of length L takes exactly L - 1 swaps.
No verified practice link yet. The guide below states the problem in full, so you can still solve it here.
The problem
You are given an array of different whole numbers. One swap exchanges any two elements. Return the fewest swaps needed
to sort the array in increasing order. For example, [10, 19, 6, 3, 5] needs 2 swaps, [2, 8, 5, 4] needs 1, and
[1, 5, 4, 3, 2] needs 2.
This problem is from Love Babbar's 450 sheet, and this guide has no verified link for it yet. The function name
minSwaps is this guide's own. All values are different.
Think first
- Sort a copy. For each value, at which index must it end up?
- Start at an index, go to the home of the value there, then to the home of the value you find, and so on. What shape do you trace?
- How many swaps does it take to fix a loop of three values that are each in the next one's place?
Hints
Brute force, and why it fails
Search over all sequences of swaps (breadth-first): exponential, but this guide uses it to check small tests. Selection sort that swaps only when the smallest remaining value is out of place also uses the fewest swaps, in O(n²) time. Counting cycles is O(n log n), for the sort.
The key insight
The swaps needed depend only on the cycles of "value → home". A cycle of L values needs exactly L - 1 swaps, so the answer is n minus the number of cycles.
Dry run
arr = [10, 19, 6, 3, 5]. Sorted it is [3, 5, 6, 10, 19], so the homes are 3 at 0, 5 at 1, 6 at 2, 10 at 3 and 19 at 4.
The plan
home = map from each value to its index in sorted(arr)
seen = all false, swaps = 0
for i from 0 to n - 1:
length = 0, j = i
while not seen[j]:
seen[j] = true
j = home[arr[j]]
length = length + 1
if length > 0: swaps = swaps + (length - 1)
return swaps
Complexity
- Time
O(n log n)- Space
O(n)
Sorting the copy is O(n log n). Every index is visited once while tracing cycles. The copy, the map and the seen
array take O(n).
Edge cases
- Already sorted: every cycle has length 1, so 0 swaps.
- One element: 0.
- Reversed, as in
[4, 3, 2, 1, 7, 6, 5]: pairs swap with each other, giving 3 swaps.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public int minSwaps(int[] arr) {
int n = arr.length;
int[] sorted = arr.clone();
Arrays.sort(sorted);
Map<Integer, Integer> home = new HashMap<>(); // value -> index it must end up at
for (int i = 0; i < n; i++) home.put(sorted[i], i);
boolean[] seen = new boolean[n];
int swaps = 0;
for (int i = 0; i < n; i++) {
int length = 0;
int j = i;
while (!seen[j]) { // follow the cycle: j's value must go to home[value]
seen[j] = true;
j = home.get(arr[j]);
length++;
}
if (length > 0) swaps += length - 1; // a cycle of length L needs L - 1 swaps
}
return swaps;
}
}C++
class Solution {
public:
int minSwaps(vector<int>& arr) {
int n = static_cast<int>(arr.size());
vector<int> sorted = arr;
sort(sorted.begin(), sorted.end());
unordered_map<int, int> home; // value -> index it must end up at
for (int i = 0; i < n; i++) home[sorted[i]] = i;
vector<bool> seen(n, false);
int swaps = 0;
for (int i = 0; i < n; i++) {
int length = 0;
int j = i;
while (!seen[j]) { // follow the cycle: j's value must go to home[value]
seen[j] = true;
j = home[arr[j]];
length++;
}
if (length > 0) swaps += length - 1; // a cycle of length L needs L - 1 swaps
}
return swaps;
}
};Python
class Solution:
def minSwaps(self, arr: list[int]) -> int:
home = {v: i for i, v in enumerate(sorted(arr))} # value -> index it must end up at
seen = [False] * len(arr)
swaps = 0
for i in range(len(arr)):
length, j = 0, i
while not seen[j]: # follow the cycle: j's value must go to home[value]
seen[j] = True
j = home[arr[j]]
length += 1
if length > 0:
swaps += length - 1 # a cycle of length L needs L - 1 swaps
return swapsCommon mistakes
- Counting adjacent swaps (as in bubble sort). Here a swap may exchange any two positions.
- Adding L instead of L - 1 per cycle.
- Using this method with repeated values. Then a value has several possible homes, and the cycles are not unique.