I'm trying to solve this challenge, which consists of finding the next biggest number formed by the digits of the passed in number. If it is impossible to find a number larger than the passed in parameter by rearranging the digits, return -1.
EX: nextBigger(12) === 21
nextBigger(2017) === 2071
nextBigger(987654321) === -1
My solution works, but they are testing a bunch of really long numbers that are causing it to time out. I don't even get to see what these really long numbers are because it times out and doesn't return any test cases. I was wondering what could be done to optimize this further.
function nextBigger(n){
let numString = n.toString();
let permutations = []
let smallest = numString[0];
let descending = true;
let same = true;
for(let i = 1; i < numString.length;i++){
if(numString[i-1] < numString[i]){
descending = false;
}
if(numString[i-1] != numString[i]){
same = false;
}
if(smallest > numString[i]){
smallest = numString[i]
}
}
if(descending || same){
return -1;
}
const permute = (prefix, str) => {
let index = String(str).length;
if(index == 1){
permutations.push( prefix + str );
}
for(let i = 0; i < index; i++){
permute(prefix + str[i], str.slice(0,i) + str.slice(i+1,index))
}
}
let nextBiggest = Infinity;
for(let i = numString.length - 2; i >= 0; i--){
let start = numString.slice(0,i);
let end = numString.slice(i,numString.length)
permute(start,end)
for(let j = 0; j < permutations.length; j++){
if(permutations[j] > n && permutations[j] < nextBiggest){
nextBiggest = permutations[j];
}
}
if(smallest == numString[i]){
return nextBiggest
}
permutations = [];
}
return -1
}
console.log(nextBigger(28554))
//42558
console.log(nextBigger(1961821))
//1962118
console.log(nextBigger(12))
//21
console.log(nextBigger(1111))
//-1
console.log(nextBigger(987654321))
//-1
console.log(nextBigger(1211))
? \$\endgroup\$for(let i...
as V8 wraps the for loop in ado not optimise
flag if you declare a block scoped variable in one of the for statements. Use vars it will improve performance on V8, though for everything but the for loop the improvement is marginal. \$\endgroup\$