Next Permutation

Medium

Topics
ArrayTwo Pointers

Rearrange nums into the lexicographically next greater permutation. If no greater permutation exists, rearrange to the lowest order (sorted ascending). Return the resulting array. Do it in-place with O(1) extra memory.

Example 1

before123
after132
pivotswapped with
The suffix after the pivot is already descending, so it is the largest arrangement of those values — nothing there can increase. The pivot is therefore swapped with the smallest value to its right that still beats it, and the suffix is then reversed to its smallest order.
Top row is the input; below it the next permutation.
Input:  nums = [1,2,3]
Output: [1,3,2]

Example 2

before321
after123
The whole array is descending, so this is the last permutation and the answer wraps to the smallest — the fully reversed array.
Input:  nums = [3,2,1]
Output: [1,2,3]

Example 3

before115
after151
pivotswapped with
Input:  nums = [1,1,5]
Output: [1,5,1]

Constraints

  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 100
Editorial — intuition, approach, complexity and pitfalls

Intuition

Read the array from the right. A suffix that descends throughout is already the largest arrangement of its values, so no amount of rearranging inside it produces something bigger. Walk left until the first position i that is smaller than its right neighbour — that is the pivot, the only place where an increase is possible at all.

Bump the pivot as little as possible: swap it with the smallest value to its right that still exceeds it, which (because the suffix descends) is the rightmost such value. Then make the suffix as small as possible. It is descending, so reversing it is enough — no sort needed.

Approach

  1. Scan from the right for the first i with nums[i] < nums[i+1].
  2. If no such i exists the whole array descends; skip to the reverse, which turns it into the ascending minimum.
  3. Otherwise scan from the right for the first j with nums[j] > nums[i] and swap the two.
  4. Reverse the suffix after i, using two pointers.

Dry Run

nums = [1,3,5,4,2]

pivot scan from the right: first index smaller than its neighbour is i=1 (value 3)
  suffix [5,4,2] is descending, so it is already maximal

rightmost value greater than 3 is at j=3 (value 4)
  after swap                  [1,4,5,3,2]
  after reversing the suffix  [1,4,2,3,5]

answer [1,4,2,3,5]

Complexity

  • Time — O(n): three passes at worst, each over a slice of the array.
  • Space — O(1) — but only if the suffix reverse uses two pointers. A slice assignment such as nums[i+1:] = reversed(nums[i+1:]) materialises a copy of the suffix and gives up the claim the problem explicitly asks for. The shown solution uses two pointers and says so in a comment.

Common Pitfalls

  • Using > instead of >= in the pivot scan. The scan then stops on a plateau of equal values, and the following j scan walks off the front of the array — on [1,1] it raises an index error rather than returning [1,1].
  • Using < instead of <= in the j scan. On [1,5,1] that swaps the pivot with an equal value and returns [1,1,5]; the correct next permutation is [5,1,1].
  • Sorting the suffix instead of reversing it. The result is right, but it is O(n log n) for work that a reversal does in O(n) — and it signals you have not noticed the suffix is already ordered.
  • Forgetting the all-descending case. Here it falls out for free: i = -1 makes i + 1 = 0, so the reverse covers the whole array.
  • Generating permutations in order and picking the next one. That is factorial time for a problem with a three-step linear answer.

Full Solution — all languages

class Solution:
    def nextPermutation(self, nums):
        # 1. walk back to the first index that can be increased
        i = len(nums) - 2
        while i >= 0 and nums[i] >= nums[i + 1]:
            i -= 1
        # 2. swap it with the rightmost value greater than it
        if i >= 0:
            j = len(nums) - 1
            while nums[j] <= nums[i]:
                j -= 1
            nums[i], nums[j] = nums[j], nums[i]
        # 3. reverse the suffix, which is descending, to make it the smallest.
        #    Two pointers rather than nums[i+1:] = reversed(nums[i+1:]) -- the slice
        #    builds a copy of the suffix and gives up the O(1) space claim.
        left, right = i + 1, len(nums) - 1
        while left < right:
            nums[left], nums[right] = nums[right], nums[left]
            left += 1
            right -= 1
        return nums
SensAI
Beta
Tap the mic to stop voice mode