Complete-Preparation

πŸŽ‰ One-stop destination for all your technical interview Preparation πŸŽ‰

View the Project on GitHub

31. Next Permutation 🌟🌟

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

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

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

Brute Force

O(N) Time solution.

Code

class Solution {
public:
    void nextPermutation(vector<int>& nums)
    {
        int n = nums.size(), k, l;
        for (k = n - 2; k >= 0; k--) { // Step 1
            if (nums[k] < nums[k + 1]) {
                break;
            }
        }
        if (k < 0) {
            reverse(nums.begin(), nums.end());
        } else {
            for (l = n - 1; l > k; l--) { // Step 2
                if (nums[l] > nums[k]) {
                    break;
                }
            }
            swap(nums[k], nums[l]); //Step 3
            reverse(nums.begin() + k + 1, nums.end()); //Step 4
        }
    }
};

Inbuilt next_permutation

Code

class Solution {
public:
    void nextPermutation(vector<int>& nums){
        next_permutation(nums.begin(), nums.end());
    }
};