Hackerrank Minimum swaps 2 – loop goes to infinity from a small change in code

Question:

This challenge asks that you find the minimum number of swaps to sort an array of jumbled consecutive digits to ascending order. This is the correct function for the question:

def minimumSwaps(arr):
    n = 0
    i =0
    while i < len(arr):
        index = arr[i]-1
        if arr[i] != arr[index]:
            arr[i], arr[index] = arr[index], arr[i]
            n+=1
            print(arr)
        else:
            i+=1
    
    return n

However if I get rid of the index = arr[i]-1 and replace index with arr[i]-1 everywhere like this:

def minimumSwaps(arr):
    n = 0
    i =0
    while i < len(arr):
        
        if arr[i] != arr[arr[i]-1]:
            arr[i], arr[arr[i]-1] = arr[arr[i]-1], arr[i]
            n+=1
            print(arr)
        else:
            i+=1
    
    return n

The loop goes to infinity and I cant figure out why this is the case.
Any help will be appreciated.

Asked By: Avighna Jha

||

Answers:

arr[i], arr[arr[i]-1] = arr[arr[i]-1], arr[i] first evaluates the rhs terms arr[arr[i]-1], arr[i] this is unchanged compared to using index, now think of them being stored in temporary variables a and b. Then it assigns to the lhs terms one by one. First a to arr[i] and only after assigns b to arr[arr[i]-1], at this stage arr[i] has alreday changed so this is no longer equivalent to using index.

Answered By: Julien
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.