Minimum Swaps 2

  • + 0 comments

    Python code.

    Final ordered array should look like [1, 2, 3, ...], so we can iterate through the array and check if current value matches index+1. If they do not match, find the index of the value that matches index+1. Then swap the values at the current index and the other index and record the swap.

    Note: this code wouldn't work if the array isn't consecutive but it seems like all the test case arrays are consecutive now.

    def minimumSwaps(arr):
        temp = 0
        swap = 0
        for x in range(len(arr) - 1):
            if arr[x] != x + 1:
                min_index = arr.index(x + 1)
                temp = arr[x]
                arr[x] = x + 1
                arr[min_index] = temp
                swap += 1
        return swap