Minimum Swaps 2

  • + 27 comments

    Here's a python3 solution that does not assume consecutive values but does assume that values aren't repeated. None of the test cases time out because it looks up indexes to swap using a hash table instead of the list.index method.

    def minimumSwaps(arr):
        ref_arr = sorted(arr)
        index_dict = {v: i for i,v in enumerate(arr)}
        swaps = 0
        
        for i,v in enumerate(arr):
            correct_value = ref_arr[i]
            if v != correct_value:
                to_swap_ix = index_dict[correct_value]
                arr[to_swap_ix],arr[i] = arr[i], arr[to_swap_ix]
                index_dict[v] = to_swap_ix
                index_dict[correct_value] = i
                swaps += 1
                
        return swaps