Skip to content

Instantly share code, notes, and snippets.

@abrarShariar
Created March 29, 2020 03:33
Show Gist options
  • Save abrarShariar/8f4395d44029fddfdb4a9fb4d7816c5c to your computer and use it in GitHub Desktop.
Save abrarShariar/8f4395d44029fddfdb4a9fb4d7816c5c to your computer and use it in GitHub Desktop.
Minimum swap final code
def minimumSwaps(arr):
if len(arr) == 1:
return 0
swapCount = 0
position = 1
n = len(arr)
# map position to element
posMap = {}
for i in range(1, n+1):
posMap[i] = arr[i-1]
# create isVisited list
isVisited = [False] * (n+1)
# loop over and find cycle
for pos in range(1, n+1):
# if a node is already visited there is no point in computing anything -> just skip
if (not(isVisited[pos])):
isVisited[pos] = True
if pos == posMap.get(pos):
continue
else:
c = posMap.get(pos)
while (not(isVisited[c])):
isVisited[c] = True
swapCount += 1
c = posMap.get(c)
return swapCount
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment