I have been trying to solve this question.
Given an unordered array consisting of consecutive integers [1, 2, 3, …, n], find the minimum number of two-element swaps to sort the array.
I was able to solve it but my solution's complexity is not good enough that it terminated due to a timeout when it runs with bigger arrays. This is a typical problem for me, I always solve the problem somehow but the complexity is not optimal and the solution does not pass the all the cast cases. If you have any suggestions for me for the future interview questions like that, I'd appreciate knowing how should I approach the questions.
function findIndice(arr,i){
let iterator=0
while(arr[iterator]!==i+1){
iterator++
}
return iterator
}
function swap(arr,x,y){
let temp=arr[x]
arr[x]=arr[y]
arr[y]=temp
}
function minimumSwaps(arr){
let i=0;
let counter=0;
let size=arr.length;
for(i=0;i<size-1;i++){
if(arr[i]!==i+1){
let index=findIndice(arr,i)
swap(arr,index,i)
counter++
}
}
return counter
}