logo CodeStepByStep logo

nextPermutation

Language/Type: JavaScript algorithms arrays interview

Write a function named nextPermutation that accepts an array of integers and rearranges its elements into the next permutation of that array's values in numerical order. For example, consider the array [1, 2, 3]. The permutations of this array, arranged in numerical order, are:

[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]

So if your function were called and passed the array [2, 1, 3], you would rearrange it to [2, 3, 1], which is the next permutation listed above. If you are passed the last permutation in numerical order, [3, 2, 1], rearrange it into the first permutation, [1, 2, 3].

As another example, if passed [1, 2, 7, 8, 6, 5, 4, 3], your function should modify the array to store [1, 2, 8, 3, 4, 5, 6, 7].

Function: Write a JavaScript function as described, not a complete program.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.