Next Permutation Problem
Description
LeetCode Problem 31.
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such an arrangement is not possible, it must rearrange it as the lowest possible order (i.e., sorted in ascending order).
The replacement must be in place and use only constant extra memory.
Example 1:
Input: nums = [1,2,3]
Output: [1,3,2]
Example 2:
Input: nums = [3,2,1]
Output: [1,2,3]
Example 3:
Input: nums = [1,1,5]
Output: [1,5,1]
Example 4:
Input: nums = [1]
Output: [1]
Constraints:
- 1 <= nums.length <= 100
- 0 <= nums[i] <= 100
Solution
Approach: Find the Pivot, Swap, Reverse
Listing all permutations to find the next one takes O(n!) time. Instead, change as little as possible, as far to the right as possible.
Read the array from the right. As long as the numbers keep rising (from right to left), that suffix is already in its largest order, so no rearrangement of it alone gives a bigger number. The first position i where nums[i] < nums[i + 1] is the place that has to grow.
- Find the rightmost
iwithnums[i] < nums[i + 1]. - If there is one, find the rightmost
j > iwithnums[j] > nums[i](the smallest number in the suffix that is still bigger thannums[i]) and swapnums[i]andnums[j]. - Reverse the suffix after
i. It was in descending order, and it still is after the swap, so reversing makes it ascending: the smallest arrangement.
If no such i exists, the whole array is descending (the last permutation), and step 3 with i = -1 reverses all of it into the first one.
Example: [1, 5, 8, 4, 7, 6, 5, 3, 1]. The pivot is 4 (index 3), the rightmost larger number after it is 5. Swapping gives [1, 5, 8, 5, 7, 6, 4, 3, 1], and reversing the suffix gives [1, 5, 8, 5, 1, 3, 4, 6, 7].
Use >= and <= in the two scans so that equal numbers (like [1, 5, 1]) are skipped correctly.
Complexity: O(n) time, where n is the length of nums, and O(1) extra space.
class Solution:
def nextPermutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
# 1. Find the rightmost i with nums[i] < nums[i + 1]; everything after i is non-increasing.
i = len(nums) - 2
while i >= 0 and nums[i] >= nums[i + 1]:
i -= 1
if i >= 0:
# 2. Swap nums[i] with the rightmost element that is larger than it.
j = len(nums) - 1
while nums[j] <= nums[i]:
j -= 1
nums[i], nums[j] = nums[j], nums[i]
# 3. Reverse the suffix after i so it becomes the smallest order (ascending).
left, right = i + 1, len(nums) - 1
while left < right:
nums[left], nums[right] = nums[right], nums[left]
left += 1
right -= 1