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.
swaps = 0
# track current positions separate from array
current_positions = {value:position for position,value in enumerate(arr)}
# +1 to indexes for intuitiveness
for k in current_positions.keys():
current_positions[k] += 1
for p,v in enumerate(arr):
if v != (p+1):
# iterate from smallest to largest int
# extract the position of the current int
# swap the positions in the dictionary
# swap the numbers in the array to match -> ensures no missed swaps when iterating from smallest to largest
current_position = current_positions[v] #returns index (plus 1)
swapped_position = current_positions[(p+1)] #returns index (plus 1)
current_positions[v], current_positions[(p+1)] = current_positions[(p+1)], current_positions[v]
arr[(current_position-1)], arr[(swapped_position-1)] = arr[(swapped_position-1)], arr[(current_position-1)]
swaps += 1
return swaps
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 →
Python3 solution