SDE & MLE Prep

31. Next Permutation

Problem

Rearrange nums in place into the next lexicographically greater permutation of its values. If it is already the largest permutation, wrap around to the smallest one (ascending order).

Example: [1,2,3] → [1,3,2]; [3,2,1] → [1,2,3]; [1,1,5] → [1,5,1]

Constraints: O(1) extra space.

From the right, find the first index i with a[i] < a[i+1] (the "pivot"). Swap it with the rightmost element larger than it, then reverse the suffix (it was descending → make it ascending). No pivot → reverse the whole array.

1 3 5 4 2      pivot 3 (3 < 5), rightmost > 3 is 4
1 4 5 3 2      swap
1 4 2 3 5      reverse suffix after pivot

Complexity: O(n) time, O(1) space.

class Solution:
    def nextPermutation(self, nums: List[int]) -> None:
        i = len(nums) - 2
        while i >= 0 and nums[i] >= nums[i + 1]:
            i -= 1
        if i >= 0:
            j = len(nums) - 1
            while nums[j] <= nums[i]:
                j -= 1
            nums[i], nums[j] = nums[j], nums[i]
        nums[i + 1:] = reversed(nums[i + 1:])