Showing:
Handle Score
@Ibrahim Nash 6420
@mb1973 5604
@Quandray 5231
@akhayrutdinov 5111
@saiujwal13083 4510
@sanjay05 3762
@kirtidee18 3673
@marius_valentin_dragoi 3522
@sushant_a 3459
@verma_ji 3413
Minimum Swaps to Sort
Medium Accuracy: 50.0% Submissions: 44626 Points: 4

Given an array of n distinct elements. Find the minimum number of swaps required to sort the array in strictly increasing order.

Example 1:

Input:
nums = {2, 8, 5, 4}
Output:
1
Explaination:
swap 8 with 4.

Example 2:

Input:
nums = {10, 19, 6, 3, 5}
Output:
2
Explaination:
swap 10 with 3 and swap 19 with 5.

You do not need to read input or print anything. Your task is to complete the function minSwaps() which takes the nums as input parameter and returns an integer denoting the minimum number of swaps required to sort the array. If the array is already sorted, return 0.

Expected Time Complexity: O(nlogn)
Expected Auxiliary Space: O(n)

Constraints:
1 ≤ n ≤ 105
1 ≤ numsi ≤ 106

to report an issue on this page.

### Editorial

We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial?