Skip to content

Link to Question

MEDIUM

Next Permutation

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 (i.e., sorted in ascending order).

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

Example

Input:

nums = [1,2,3]

Output:

[1,3,2]

Explanation:
The next permutation of [1,2,3] is [1,3,2].


Constraints

  • 1 ≤ nums.length ≤ 100

Solution: Two Pointers

  • Time Complexity: O(n)
  • Space Complexity: O(1)
C++
class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        int n = nums.size(), k;
        for(k = n - 2; k >= 0; k--)
            if (nums[k] < nums[k+1]) break;
        if (k >= 0) {
            int l;
            for (l = n - 1; l >= 0; l--)
                if (nums[l] > nums[k]) break;
            swap(nums[l], nums[k]);
        }
        reverse(nums.begin() + k + 1, nums.end());
    }
};