Skip to content

Instantly share code, notes, and snippets.

@dovideh
Last active January 14, 2020 18:22
Show Gist options
  • Save dovideh/4d8bf0d9b63a69d96a8bbd35920b314e to your computer and use it in GitHub Desktop.
Save dovideh/4d8bf0d9b63a69d96a8bbd35920b314e to your computer and use it in GitHub Desktop.
Minimum Swaps 2 - HR
#!/bin/python
import math
import os
import random
import re
import sys
# Complete the minimumSwaps function below.
def minimumSwaps(arr):
i = 0
swp = 0
d = dict((val, idx) for val,idx in enumerate(arr))
last = len(arr)-1
while (True):
value_idx = d[i]-1
key = i
if (d[i] != i+1):
if value_idx == i+1:
i+=1
else:
d[key],d[value_idx] = d[value_idx],d[key]
swp +=1
elif(d[i] == i+1):
if(d[i] != last):
i+=1
else:
break
return swp
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
arr = list(map(int, input().rstrip().split()))
res = minimumSwaps(arr)
fptr.write(str(res) + '\n')
fptr.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment