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 figure an index map can make it a whole a lot easier and straight forward:
functionminimumSwaps(arr){constindexMap={};arr.forEach((element,index)=>{indexMap[element]=index;});letswap=0;for(leti=0;i<arr.length;i++){//If the index doesn't match value, swapif(arr[i]!==i+1){consttarget=i+1;//1constcurrTargetIndex=indexMap[target];//index = 3//swap and keep track of the index mapindexMap[target]=i;indexMap[arr[i]]=currTargetIndex;arr[currTargetIndex]=arr[i];arr[i]=target;swap+=1;}}returnswap;}
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 figure an index map can make it a whole a lot easier and straight forward: