Next Permutation in Python

class Solution:
    def nextPermutation(self, nums: List[int]) -> None:
        """
        Modify nums in-place to its next permutation.
        """
        # Step 1: Find the pivot
        i = len(nums) - 1
        while i > 0 and nums[i - 1] >= nums[i]:
            i -= 1

        if i > 0:
            # Step 2: Find the successor to pivot
            j = len(nums) - 1
            while nums[j] <= nums[i - 1]:
                j -= 1

            # Step 3: Swap
            nums[i - 1], nums[j] = nums[j], nums[i - 1]

        # Reverse the elements from i to the end of the array
        nums[i:] = reversed(nums[i:])

PrevNext