We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
My solution is more verbose but it is similar to yours, gets all test cases right and is only requesting the sequence to be not containing any duplicates. Gaps in the sequence are okay and the sequence may also start at any non-negative value
# Complete the minimumSwaps function below.defminimumSwaps(arr):#principle: trying to swap with maximum impact#iterations (reads) are cheap, swapping expensive#if two values can be swapped where both receive terminal position afterwards, perfectswaps=0min=Noneforiinarr:ifminisNoneormin>i:min=i#defined a min, which is at 0, let's make sure it's at i=0min_i=arr.index(min)ifmin_iisnot0:swap(arr,0,min_i)swaps+=1#because the minimum is at 0 and they are all consecutive, it's basically an offsetoffset=arr[0]#initializing a dict copy that keeps track of the locations for quick find and swapindex_dict={v:ifori,vinenumerate(arr)}#starting at 1, 0 is already placedi=0whilei<len(arr)-1:i+=1ifnotproper_place(arr,i,offset):try:val=arr[i]#testing for perfect swapifarr[val-offset-1]==i:swap(arr,i,val-offset)swaps+=1#no perfect swap possible, find item that belongs here and swap this one awayelse:j=index_dict[i+offset]index_dict[arr[i]]=jswap(arr,i,j)swaps+=1except:passreturnswapsdefproper_place(arr,i,min):returnarr[i]-min==idefswap(arr,a,b):t=arr[a]arr[a]=arr[b]arr[b]=t
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Minimum Swaps 2
You are viewing a single comment's thread. Return to all comments →
My solution is more verbose but it is similar to yours, gets all test cases right and is only requesting the sequence to be not containing any duplicates. Gaps in the sequence are okay and the sequence may also start at any non-negative value