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.
Came up with a pretty easy solution. You don't have to keep temporary variables, swap etc. since it's memory wasting for larger arrays.
All you have to do is iterate through the array and check the current value. If it's in the wrong place, find the value that has to be in that place and substitute it with th current value. Since by doing this you will create duplicate values, in JS i used the lastIndexOf() method to ignore the values with index less than the current in check.
functionminimumSwaps(arr){//Set swaps to zeroletswaps=0;//Iterate arrfor(leti=0;i<arr.length-1;i++){//Is the current element at the wrong place?if(arr[i]!==i+1){//Substitute the element that has to be here with the current elementarr[arr.lastIndexOf(i+1)]=arr[i];//Incrementswaps++;}}//Returnreturnswaps;}
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 →
Came up with a pretty easy solution. You don't have to keep temporary variables, swap etc. since it's memory wasting for larger arrays. All you have to do is iterate through the array and check the current value. If it's in the wrong place, find the value that has to be in that place and substitute it with th current value. Since by doing this you will create duplicate values, in JS i used the lastIndexOf() method to ignore the values with index less than the current in check.