Previous Permutation CPP | TC:O(n) | SC: O(1)

This post discuss about Implementation previous permutation, which rearranges numbers into the lexicographically just smaller than given premuation.

The solution approach is similar to Next permutation solution by @jianchao-li.

Find the largest index k such that nums[k] > nums[k + 1]. If no such index exists, just reverse nums and done.
Find the largest index l > k such that nums[k] > nums[l].
Swap nums[k] and nums[l].
Reverse the sub-array nums[k + 1: ].

 void prevPermutation(vector<int>& nums) {

    int n = nums.size();
    int k, l;
    for(k=n-2; k>=0; k--){
        if(nums[k] > nums[k+1])
            break;    
    }

    if(k<0){
        reverse(nums.begin(), nums.end());
        return;
    }

    for(l=n-1; l>k; l--){
        if(nums[k] > nums[l])
            break;
    }

    swap(nums[k], nums[l]);

    reverse(nums.begin() + k + 1, nums.end());
}
Comments (0)