Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

262
Views
Math Challenge print the next largest number after shuffling using javascript

Have the function nextLargest(num) take the num parameter being passed and return the next number greater than num using the same digits. For example: if num is 123 return 132, if it's 12453 return 12534. If a number has no greater permutations, return -1 (ie. 999).

Examples

Input: 11121
Output: 11211
Input: 41352
Output: 41523
var permute = (function () {
    return permute;

    function permute(list) {
        return list.length ?
            list.reduce(permutate, []) :
            [[]];
    }
    
    function permutate(permutations, item, index, list) {
        return permutations.concat(permute(
            list.slice(0, index).concat(
            list.slice(index + 1)))
            .map(concat ,[item]));
    }
    
    function concat(list) {
        return this.concat(list);
    }

}());

console.log(JSON.stringify(permute([1,2,3,4])));

my output : [[1,2,3,4],[1,2,4,3],[1,3,2,4],[1,3,4,2],[1,4,2,3],[1,4,3,2],[2,1,3,4],[2,1,4,3],[2,3,1,4],[2,3,4,1],[2,4,1,3],[2,4,3,1],[3,1,2,4],[3,1,4,2],[3,2,1,4],[3,2,4,1],[3,4,1,2],[3,4,2,1],[4,1,2,3],[4,1,3,2],[4,2,1,3],[4,2,3,1],[4,3,1,2],[4,3,2,1]]

expected output :

Input: 11121
Output: 11211
Input: 41352
Output: 41523
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Assuming the permute function as given that you shared in your question, the following straightforward approach should solve the question.

It is not very efficient, however. Probably, a better strategy could be found working with a cleverly chosen sequence of transpositions only.

function nextLargest(input) {
  let x = input.toString();
  let p = permute([...x]);
  let result = Infinity;
  for (let n of p) {
    let y = n.join('')*1;
    if (y > input && y < result) result = y; 
  }
  return result < Infinity ? result : -1;
}
  
console.log(nextLargest(1234));  // <<< gives 1243
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!