Iam_Sandeep

Minimum number of swaps to sort array using graph

Jan 31st, 2022
935
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.96 KB | None | 0 0
  1. https://practice.geeksforgeeks.org/problems/minimum-swaps/1#
  2.  
  3. class Solution:
  4.    
  5.     #Function to find the minimum number of swaps required to sort the array.
  6.     def minSwaps(self, nums):
  7.         n=len(nums)
  8.         seen=set()
  9.         ans=0
  10.         adict=sorted(((j,i) for i,j in enumerate(nums)),key=lambda x:x[0])
  11.         for key,val in adict:
  12.             if key in seen:
  13.                 continue
  14.             seen.add(key)
  15.             swaps=0
  16.             idx=val
  17.             while adict[idx][0] not in seen:
  18.                 seen.add(adict[idx][0])
  19.                 swaps+=1
  20.                 idx=adict[idx][1]
  21.             ans+=swaps
  22.         return ans
  23.            
  24.            
  25. #{
  26. #  Driver Code Starts
  27.  
  28.  
  29. if __name__ == '__main__':
  30.     T=int(input())
  31.     for i in range(T):
  32.         n = int(input())
  33.         nums = list(map(int, input().split()))
  34.         obj = Solution()
  35.         ans = obj.minSwaps(nums)
  36.         print(ans)
  37.  
  38. # } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment