We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
I edited my original post. I think is clearer now. What the algorithm is doing is throwing (swapping) the first element of the array back to its finalPosition.
You are always checking the first element of the array, unless that number is already in its finalPosition, in which case you go to the second element and so on.
So in order to do that, we must know which it's the finalPosition of each value, and that's what the formula that you mention does.
finalPosition = (the value you are processing) - (the min value of the array)
Since we know that the input array (arr) is always in sequential order, then we only need to know the min value (the value that it's final position will be index 0) and calculate the distance between the value you'r processing and the min value.
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Minimum Swaps 2
You are viewing a single comment's thread. Return to all comments →
I edited my original post. I think is clearer now. What the algorithm is doing is throwing (swapping) the first element of the array back to its finalPosition.
You are always checking the first element of the array, unless that number is already in its finalPosition, in which case you go to the second element and so on.
So in order to do that, we must know which it's the finalPosition of each value, and that's what the formula that you mention does.
Since we know that the input array (arr) is always in sequential order, then we only need to know the min value (the value that it's final position will be index 0) and calculate the distance between the value you'r processing and the min value.