logo CodeStepByStep logo

nextPermutation

Language/Type: C++ algorithms vector interview
Related Links:

Write a function named nextPermutation that accepts a reference to a vector of integers and rearranges its elements into the next permutation of that vector's values in numerical order. For example, consider the vector {1, 2, 3}. The permutations of this vector, 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 vector {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 vector to store {1, 2, 8, 3, 4, 5, 6, 7}.

Function: Write a C++ 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.