Minimum Swaps to Sort

Problem Statement

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.

Your Task: 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

Intuition

We intend to send all elements to the correct position

Hence, Maintain a array where we sort the array
MAintain a map which contains actual position of elements, 
Can iterate over this sorted and maintain the indices

Now compare the actual array with sorted and start sending the elements to the
correct position

You notice we can send them in min swaps

https://practice.geeksforgeeks.org/problems/minimum-swaps/1

Approach 1:

Map and sorting
C++

class Solution 
{
    public:
	int minSwaps(vector<int>&nums){
	    vector<int> arr(nums);
        unordered_map<int,int> mp;
        sort(arr.begin(), arr.end());
        int count = 0;

        for(int i=0; i<arr.size(); i++)
            mp[arr[i]] = i;

        int left = 0;
        int right = 0;

        while(right < arr.size()){
            if(arr[left] != nums[right]){
                int pos = mp[nums[right]];
                swap(nums[right], nums[pos]);
                count++;
            }

            else{
                left++;
                right++;
            }
        }
        
        return count;
	}
};

Approach 2:

C++

Approach 3:

C++

Approach 4:

C++

Similar Problems

Last updated