In this challenge, the goal is to determine the minimum number of swaps needed to arrange an array of disordered consecutive digits in ascending order. My code successfully handles most of the tests, but I'm encountering timeout errors with four specific cases. Can anyone help pinpoint why my code is timing out? Is there a more efficient approach that could provide quicker results?
function minimumSwaps(arr) {
const min = Math.min(...arr);
let swapCount = 0;
const swap = (array, a, b) => {
let temp = array[a];
array[a] = array[b];
array[b] = temp;
}
for(let i=0; i<arr.length; i++){
if(arr[i]!==i+min){
swap(arr, i, arr.indexOf(i+min));
swapCount++;
}
}
return swapCount;
}
I initially believed my solution was efficient as it only requires a single iteration over the array's length. I am eager to gain insights into why this implementation isn't meeting performance expectations.