Minimum Swaps 2

  • + 1 comment

    Python3 solution

    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