Lily's Homework

  • + 0 comments

    Just sort and count number of swaps required to get the sorted array For some test cases reverse of sorted array gives minimum swaps. So I have calculated swaps for both sorted ones and its reverse

    def lilysHomework(arr):
        # Write your code here
        arrs=sorted(arr)
        d1={}
        d2={}
        for i in range(len(arr)):
            d1[arr[i]]=arrs[i]
            d2[arr[i]]=arrs[len(arr)-1-i]
        
        return min(getswaps(d1),getswaps(d2))
        
        
    
    def getswaps(d):
        swap=0
        for x in d.keys():
            y=d[x]
            while(x!=y):
                swap+=1
                d[x]=d[y]
                d[y]=y
                y=d[x]
                
        return swap