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.
My JavaScript (JS/node.js) solution.
This assumes the first number may not start at 1.
// Complete the minimumSwaps function below.functionminimumSwaps(arr){letswaps=0;// Counter for minimum number of swaps// bubble sortletindex=0;// Find the lowest value in the array:constminimum=Math.min(...arr);while(index<arr.length){// Subtract 1 from the element to determin it's correct position in the arrayconstelementAsIndex=arr[index]-1;// Because the numbers are consecutive, but may not start at 1,// we can determin what the correct number is for our current index by...// adding the minimum value and adding the index. We subtract 1 to get the position.constlocationInArray=index+minimum-1;// Check if element is greater or less than it's position in the arrayif(elementAsIndex!==locationInArray){swaps+=1;// Swap the elements[arr[elementAsIndex],arr[locationInArray]]=[arr[locationInArray],arr[elementAsIndex]];}else{index+=1;}}// key element is consecutive... does it always start at 1?returnswaps;}
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 →
My JavaScript (JS/node.js) solution. This assumes the first number may not start at 1.