Minimum Swaps to Sort | Practice | GeeksforGeeks

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
0
binnukaniki1234 days ago
class Pair{   int n,m;   public Pair(int m,int n)   {       this.m=m;       this.n=n;   }}class Sortbyroll implements Comparator<Pair> {   // Used for sorting in ascending order of   // roll number   public int compare(Pair a, Pair b)   {       return a.m - b.m;   }}
class Solution{   //Function to find the minimum number of swaps required to sort the array.   public int minSwaps(int nums[])   {       // Code here       Pair[]arr=new Pair[nums.length];       boolean[] vis=new boolean[nums.length];       for(int i=0;i<nums.length;i++)       {           arr[i]=new Pair(nums[i],i);       }      Arrays.sort(arr, new Sortbyroll());       int ans=0;       for(int i=0;i<nums.length;i++)       {           int count=0;           if(arr[i].m==nums[i]||vis[i]==true)              continue;             int j=i;            while(vis[j]==false)            {                vis[j]=true;                count++;                j=arr[j].n;                            }            ans+=(count-1);       }       return ans;   } }
0
ashishaks02114 days ago
int minSwaps(vector<int>&nums)
	{
	    map<int,int> mp;
	    for(int i = 0;i<nums.size();i++)
	        mp[nums[i]] = i;
	    sort(nums.begin(),nums.end());
	    int ans = 0;
	    for(int i = 0;i<nums.size();i++){
	        while(mp[nums[i]]!=i){
	        ans++;
	        int temp = nums[i];
	        nums[i] = nums[mp[temp]];
	        nums[mp[temp]]  = temp;
	        }
	    }
	    return ans;
	}
0
harshscode1 week ago
idea is first sort and compare to unsort if position is mismatch then swap and count...............
 
  int minSwaps(vector<int>&nums){    vector<pair<int,int>> v(nums.size());    for(int i=0;i<nums.size();i++)    v[i]={nums[i],i};        sort(v.begin(),v.end());        int cnt=0;    for(int i=0;i<nums.size();i++)    {        if(i==v[i].second)        continue;        else        {            cnt++;            swap(v[i],v[v[i].second]);            i--;        }    }        return cnt;     }
0
shubham211019972 weeks ago
 int minSwaps(vector<int>&nums)
{
    vector<pair<int,int>> vec;
   int n=nums.size();
   for(int i=0;i<n;i++)
   {
       vec.push_back({nums[i],i});
   }
   sort(vec.begin(),vec.end());
   vector<bool>vis(n,0);
 int ans=0;
   for(int i=0;i<n;i++)
   {   
         int clen=0;
       if(vis[i]==1||vec[i].second==i)
       continue;
       
       int j=i;
       while(vis[j]==false)
       {
           vis[j]=true;
           clen++;
           j=vec[j].second;
       }
       ans+=clen-1;
   }
   
   return ans;
}
0
atharvapatil68482 weeks ago
int count = 0;
transfer all elements in new array a[] ,sort a,compare both the array if elements are changed count++,return count/2;
what is the problem in this solution?
0
user_udl52 weeks ago
def minSwaps(self, nums):       temp = sorted(nums)       mapp = {}       swaps = 0       num_len = len(nums)       for i in range(num_len):           mapp[nums[i]] = i                  for i in range(num_len):           if nums[i] == temp[i]: # element already in their place               continue           else:               init = nums[i]                #swapping the elements of input array to their correct pos                              nums[i], nums[mapp[temp[i]]] = nums[mapp[temp[i]]], nums[i]               swaps += 1               # updating map values after swapping               mapp[init] = mapp[temp[i]]               mapp[temp[i]] = i       return swaps   # in the above approach im trying to sort the input array by the help   # of sorted copy of input array(temp) and a dictionary which is storing the    # input array elements as key and its index as values associated with key   # 
0
amanjugran12 weeks ago
Simple python Solution (All test cases passed)
 
def minSwaps(self, nums): arr = sorted(nums) dic={} for i in range(len(nums)):     dic[nums[i]] = i c=0 for i in range(len(nums)):     if arr[i] != nums[i]:         c+=1         index = dic[arr[i]]         index2 = dic[nums[i]]         dic[arr[i]] = index2         dic[nums[i]] = index         t = nums[index]         nums[index]=nums[index2]         nums[index2]=t return c
+1
mayank20213 weeks ago
TLE : 11/50 passed.. any suggestion in this code ? int minSwaps(vector<int>&nums){    int count=0, i=0, j=nums.size()-1, k , currentmin=INT_MAX , currentmax=INT_MIN ;    int currentminindex=-1, currentmaxindex=-1,l;        while (i<j)     {               for(l=i ; l<=j ; l++)       {           if(nums[l] < currentmin )             {                currentmin=nums[l];                currentminindex=l;            }                       if(nums[l] > currentmax)            {currentmax =nums[l];           currentmaxindex=l;           }                  }             if(nums[i] != currentmin )          {              if(nums[i]==currentmax) currentmaxindex=currentminindex;              swap(nums[i], nums[currentminindex]);              count++;          }          i++;          if(nums[j] !=currentmax)          {              swap(nums[j], nums[currentmaxindex]);              count++;          }          j--;                   currentmin=INT_MAX , currentmax=INT_MIN;              }        return count;    }
0
for_the_luv_of_coding3 weeks ago
https://www.hackerrank.com/contests/aasf-bi-weekly-contest/challenges/big-head-is-worthy/problem
0
anupbagade20144 weeks ago
Python Solution
class Solution:
    
    #Function to find the minimum number of swaps required to sort the array.
	def minSwaps(self, nums):
		nums_sorted = sorted(nums)
		swaps_count = 0
		
        # create dictionary
        nums_dict = dict()
        for i in range(len(nums)):
            nums_dict[nums[i]] = i
		
		for i in range(len(nums)):
		    
		    if nums_sorted[i] != nums[i]:
		        idx = nums_dict[nums_sorted[i]]
		        nums[i] , nums[idx] = nums[idx], nums[i]
		        nums_dict[nums[i]] = i
		        nums_dict[nums[idx]] = idx
		        swaps_count += 1
		        
        #print(swaps_count)
        
        return swaps_count
        
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.