Javascript Solution


  • 0
    R
    /**
     * @param {string} time
     * @return {string}
     */
    var nextClosestTime = function(time) {
        var arr = time.split("");
        var done = 0;
        var limits = [2,3,0,5,9]; //limits to numbers in each respective position
        var i;
        if(parseInt(arr[0]) < 2){ // if the hour is not over 20, we can have a 9 as the second hour digit
            limits[1] = 9;
        }
        min = arr[0];
        for(i = arr.length - 1 ; i >= 0 ; i--){
            if(arr[i] == ':'){ //I didn't remove the colon from the array to make it easier to translate into a strig with the reduce function
                    continue;
            }
            if(arr[i] < min){
                min = arr[i];
            }
            var oVal = arr[i];
            for(var j = arr.length - 1 ; j >= 0 ; j--){
                if(done != i && done)
                    break;
                if(arr[j] == ':'){
                    continue;
                }
                if( 
                    parseInt(arr[j]) > parseInt(oVal) && parseInt(arr[j]) <= limits[i] //if the value of the array we're looking through is greater than the original value in the array and the value is under the max allowed digit in that position
                   && (arr[i] == oVal || parseInt(arr[j]) < parseInt(arr[i]) )  //and either we didn't change the value from the original value or the current value of the array we're looking through is less that a previously substituted value
                ){
                    arr[i] = arr[j];
                    done = i; //so I can keep track of where the digit that was changed was
                }
            }
            
        }
        
        for(var l = done + 1 ; l < arr.length ; l++){
            if(arr[l] == ':'){
                continue;
            }
            arr[l] = min;
        }
        
        if(done){
            var sum = arr.reduce(function (a, b) {
                      return a + b;
                    }, "");
            return sum;
        }
        return `${min}${min}:${min}${min}`;
        
        
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.