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)

def nextPermutation(self, nums):
    """
    :type nums: List[int]
    :rtype: void Do not return anything, modify nums in-place instead.
    """                
    for k in range(len(nums)-1, 0, -1):
        # find the first entry from the right that is larger than the previous entry
        if nums[k-1] >= nums[k]: 
            continue

        # find the smallest element on the right which is larger than nums[k-1]
        l = len(nums) - 1
        while nums[k-1] >= nums[l]:
            l -= 1

        # swap these two elements
        nums[k-1], nums[l] = nums[l], nums[k-1]

        # reverse the element on the right
        nums[k:] = reversed(nums[k:])
        return

    nums.reverse()

Last updated