31_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 (ie, sorted in ascending order).

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

Example

Input: [1,2,3]
Output: [1,3,2]

Input: [3,2,1]
Output: [1,2,3]

Input: [1,1,5]
Output: [1,5,1]

Solution

Idea

  1. find k such that nums[k-1] < nums[k] and entries after index k appear in decreasing order

  2. find the smallest nums[l] such that l>k-1, nums[l] > nums[k-1], and nums[l-1] <= nums[k-1]

  3. swap p[l] and p[k-1]

  4. reverse the sequence on the right of p[k]

Time Complexity: O(n)O(n)

Space Complexity: O(1)O(1)

Last updated

Was this helpful?