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.
The logic is very simple.
Only available elements in the array are from "1 to n " .
step 1 : check if each array index is filled is current value . ( So, arr[i] ==i+1, since, index start from 0 , so need for increment of 1 as value is from 1 to n ).
step 2 : for the element not at its actual position.
we simply replace the ith element with value at the (i-1)th position , as index is from 0 . and increase the count .
And again decreasing the i of loop to check if again the value at ith position is (i+1) or not .
finally , you will get your desired value.
thanks.
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 →
The logic is very simple. Only available elements in the array are from "1 to n " .
step 1 : check if each array index is filled is current value . ( So, arr[i] ==i+1, since, index start from 0 , so need for increment of 1 as value is from 1 to n ).
step 2 : for the element not at its actual position. we simply replace the ith element with value at the (i-1)th position , as index is from 0 . and increase the count . And again decreasing the i of loop to check if again the value at ith position is (i+1) or not .