Striver-SDE-Sheet

Repository containing solution for #SdeSheetChallenge by striver

View the Project on GitHub

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

Get all permutations with recursion
void allPermutations(vector<vector<int>> ans, vector<int> nums, int ind)
{
    if (ind == nums.size())
    {
        ans.push_back(nums);
        return;
    }
    for (int i = ind; i < nums.size(); i++)
    {
        swap(nums[ind], nums[i]);
        allPermutations(ans, nums, ind + 1);
        swap(nums[ind], nums[i]);
    }
}

O(N) Time solution.

1  2  3     2  1  3     3  1  2
1  3  2     2  3  1     3  2  1
-------------------------------
1 2 3 4     2 3 1 4     3 4 1 2
1 2 4 3     2 3 4 1     3 4 2 1
1 3 2 4     2 4 1 3     4 1 2 3
1 3 4 2     2 4 3 1     4 1 3 2
1 4 2 3     3 1 2 4     4 2 1 3
1 4 3 2     3 1 4 2     4 2 3 1
2 1 3 4     3 2 1 4     4 3 1 2
2 1 4 3     3 2 4 1     4 3 2 1

Code

class Solution {
public:
    void nextPermutation(vector<int>& nums)
    {
        int n = nums.size();
        int k, l;

        // Step-1 : find index k before peak point from end;
        for (k = n - 2; k >= 0; k--) {
            if (nums[k] < nums[k + 1]) {
                break;
            }
        }

        if (k < 0) {
            reverse(nums.begin(), nums.end());
        } else {
            // step-2: find index l (l>k) from end which have greater element than at index k;
            for (l = n - 1; l > k; l--) {
                if (nums[k] < nums[l]) {
                    break;
                }
            }

            // Step-3: swap kth and lth element
            swap(nums[k], nums[l]);

            // Step-4: reverse vector from k+1 to end
            reverse(nums.begin() + k + 1, nums.end());
        }
    }
};

Inbuilt next_permutation function

Code

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