Minimum Swaps 2

  • + 3 comments

    Gotta say, I'm very disappointed when the time constraints are such that the fastest way to solve something in Javascript continually gets a timeout. If HackerRank presents a problem then they should disable a language if they're going to put unrealistic time constraints on it.

    Heres a solution I tried that worked other than timeout:

    var rotArr = Object.values(Object.assign({}, arr));
    var minVal;
    var maxVal = Math.max(...rotArr);
    var minValInd;
    var currentVal;
    var swapCount = 0;
    
    for(var i = 0; i < rotArr.length; i++){
        // get minimum values
        minVal = Math.min(...arr);
    
        if(minVal === rotArr[i]){
            arr.shift()
            continue;
        }
    
        minValInd = rotArr.indexOf(minVal);
    
        currentVal = rotArr[i];
        rotArr[i] = rotArr[minValInd];
        rotArr[minValInd] = currentVal;
    
        arr = Object.values(Object.assign({}, rotArr.slice(i)));
        arr.shift();
    
        minVal = Math.min(...arr);
        swapCount = swapCount +1;
    }
    
    return swapCount;