Open leeway00 opened 2 years ago
res = 0
arrtemp = sorted([*enumerate(arr)], key = lambda x: x[1])
circit = {k: False for k in range(len(arr))}
for ind, val in arrtemp: #sorted based on val
if ind+1 != val and not circit[ind]:
start = ind
cycle = 0
while not circit[start]:
circit[start] = True
start = arrtemp[start][0]
cycle +=1
res += cycle -1
return res
def minimumSwaps(arr):
n = len(arr)
ans = 0
temp = arr.copy()
temp.sort() # [1,2,3,4,5]
h = {val: ind for ind, val in enumerate(arr)}
init = 0
for i in range(n):
if (arr[i] != temp[i]):
ans += 1
init = arr[i]
arr[i], arr[h[temp[i]]] = arr[h[temp[i]]], arr[i]
h[init] = h[temp[i]]
h[temp[i]] = i
return ans