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.
If you want to avoid timeout error and have a fast compute you'll need to create a map of each index based on value of the given array.
You also need to create an array sorted to know what value you should have next when you iterate and if it's not the one attended you can swap it. During the swap you need to update the map with the new index and voilà.
functionminimumSwaps(arr){letswaps=0;letl=arr.length;// Copy arrayconstarr2=[...arr];// Sorting the new array// It will be used to know what's the next value in the array// And swap if neededarr2.sort((a,b)=>{if(a>b)return1;elseif(a<b)return-1;return0;});// Create an object with values of our array as keys// and position in array as valuesconstmap=arr.reduce((acc,cur,i)=>{acc[cur]=i;returnacc;},{});// Now we loop through the arrayfor(leti=0;i<l;i+=1){constv1=arr[i];constv2=arr2[i];if(v2!=v1){swaps+=1;// Use the map to avoid to compute each time the positionconstindex=map[v2];// swap valuearr[index]=v1;arr[i]=v2;// Update mapmap[v1]=index;};}returnswaps;}
Minimum Swaps 2
You are viewing a single comment's thread. Return to all comments →
Here is my solution using Javascript.
If you want to avoid timeout error and have a fast compute you'll need to create a map of each index based on value of the given array.
You also need to create an array sorted to know what value you should have next when you iterate and if it's not the one attended you can swap it. During the swap you need to update the map with the new index and voilà.