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.
Update:
Came up with the following codes that actually works quickly enough to elude the timeout error. I don't get why is it that using the ".index" appendment on the working list (the one whose entries are being swapped around) causes such a massive slowdown in performance!
def minimumSwaps(arr):
counter = 0
ph = [0]*(len(arr))
for index,val in enumerate(arr):
ph[val-1] = index
#while arr != sorted(arr):
for i in range(len(arr)):
#for j,number2 in enumerate(arr):
#if j != i: #and (number1 - 1 - i) + (number2 - 1 - j) == m:
if (arr[i]) != i+1:
l = ph[i+1-1]
#l = arr.index(i+1)
arr[i],arr[l] = i+1,arr[i]
#the 2 corresponding entries in ph have to be updated simultaneously!
ph[i+1-1],ph[arr[l]-1] = i,l
counter += 1
return counter
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 →
Update: Came up with the following codes that actually works quickly enough to elude the timeout error. I don't get why is it that using the ".index" appendment on the working list (the one whose entries are being swapped around) causes such a massive slowdown in performance!