Minimum Swaps 2

  • + 0 comments

    simple python code. if u use for loop with this logic it won't work smh.

    def minimumSwaps(arr):
        swaps = 0
        i = 0
        while i < len(arr):
            correct_value = i + 1
            if arr[i] != correct_value:
                swap_idx = arr[i] - 1  # Where this value should be
                arr[i], arr[swap_idx] = arr[swap_idx], arr[i]
                swaps += 1
            else:
                i += 1
        return swaps