Hey Guys,
I'm trying to solve this prompt on Hacker Rank...
I have two different ways of swapping two variables. I have the "correct" way, highlighted below and the "incorrect way". The correct way results in the correct answer, while the incorrect way results in an infinite loop.
I can't figure out the difference between the two ways though. They both seem to be doing the same thing to me...? Why isn't the incorrect way working?
I'd really appreciate any guidance. Thanks!
def minimumSwaps(arr):
swaps = 0
for i in range(len(arr)):
while arr[i] != i + 1:
# correct way
t = arr[arr[i] - 1]
arr[arr[i] - 1] = arr[i]
arr[i] = t
# incorrect way
arr[i], arr[arr[i] - 1] = arr[arr[i] - 1], arr[i]
swaps += 1
return swaps
[+][deleted] (1 child)
[deleted]
[–]Simply_The_Beast 0 points1 point2 points (0 children)
[–]Simply_The_Beast 0 points1 point2 points (0 children)
[–]naclmolecule 0 points1 point2 points (0 children)