Minimum Swaps 2

  • + 4 comments

    Yeah, at first when I didnt notice that the array has to start from 1 and consecutive from there I was confuse too, since it mean we need a sorted array first to even check how many swap we will need in the end. Your 3rd step is basically a sort by itself, and if we have to sort anyway we can skip the whole normalize thing by doing this (in JS)

    var origArray = arr.slice(0); // to keep a copy of the original array
    var sortedArray = arr.sort();
    
    for(var i = 0; i < origArray.length; i++) {
    	if (origArray[i] != sortedArray[i]) {
    		for (var j = i+1; j < origArray.length; j++) {
    			if(origArray[j] === origArray[i]) {
    				swap(origArray[i],origArray[j]
    				numberOfSwap++
    				break;
    			}
    		}
    	}
    }
    

    This way we dont have to worry about normalization at all since we know exactly where each value should be after the mandatory sort either way.