Next Permutation

Jin Shang bio photo By Jin Shang

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

The replacement must be in-place and use only constant extra memory.

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.

1,2,3` → `1,3,2`
`3,2,1` → `1,2,3`
`1,1,5` → `1,5,1

Solution:

observe that array in descending order is in the highest lexicographical order.

1) Iterate from right until nums[i-1] < nums[i], then nums[i : n] is descending, so need to advance one.

1a) If none, that means nums is already highest, just reverse it.

2) Find j from i such that nums[j] just > nums[i], then nums[j] is the leading digit for next permutation.

3) Swap nums[i-1] and nums[j], then reverse nums[j] to nums[n]. Return.

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        int n = nums.size();
        int i = n-1;
        while(i>0 && nums[i-1]>=nums[i]){
            i--;
        }
        if(i==0){
            reverse(nums.begin(),nums.end());
            return;
        }
        int j = i;
        while(j<n && nums[j]>nums[i-1]){
            j++;
        }
        j--;
        swap(nums[i-1],nums[j]);
        reverse(nums.begin()+i,nums.end());
        
        return;
    }
};