Next Permutation
Next Permutation is LeetCode 31 (Medium). Rearrange the array nums into the arrangement that comes right after it in dictionary (lexicographic) order.
- If the array is already the largest arrangement, wrap around to the smallest one: the numbers in rising order.
- Work in place with O(1) extra memory.
Values may repeat, so the order is over distinct arrangements.
- 1 <= nums.length <= 100
- 0 <= nums[i] <= 100
Intuition
To get the very next arrangement, change the array as far to the right as possible, and by as little as possible.
- Find the pivot: scan from the right while the numbers keep rising toward the left. That falling tail is already the largest order of its numbers, so it cannot grow. The first number smaller than the one after it is the pivot, the rightmost position that can grow.
- Grow it by the least: swap the pivot with the smallest number in the tail that is larger than it.
- Make the tail smallest: the tail still falls after the swap, so reversing it puts it in rising order.
If no pivot exists, the whole array falls, and reversing it gives the wrap-around answer.
"The next arrangement in sorted order", in place: think rightmost rise, swap, reverse. The same three steps drive C++'s std::next_permutation, and Next Greater Element III applies them to the digits of a number.
Approach
Before reading on, list all six orders of [1, 2, 3] in sorted order and look at what changes from each one to the next. Aim for O(n) time with no extra array.
Find the pivot from the right
Start at i = n − 2 and move left while nums[i] >= nums[i + 1]. When the loop stops, nums[i] is smaller than its right neighbour; if i reaches −1, there is no pivot.
Find the swap partner
If a pivot exists, start j at the last index and move left while nums[j] <= nums[i]. The tail falls, so the first number from the right that is bigger than the pivot is the smallest such number.
Swap the pivot and the partner
Swap nums[i] and nums[j]. The pivot position now holds the smallest value that makes the array larger there, and the tail still falls from left to right.
Reverse the tail
Reverse nums[i + 1:] with two pointers moving inward. A falling run reversed becomes rising, its smallest order. With no pivot, i is −1 and the whole array is reversed, which is the wrap-around case.
Code in Python, C++ and Java
Common pitfalls
Strict comparisons with repeated values
while i >= 0 and nums[i] > nums[i + 1]:
i -= 1while i >= 0 and nums[i] >= nums[i + 1]:
i -= 1Equal neighbours do not form a rise. With >, [1, 5, 5] stops at index 1 and treats the 5 as a pivot; the partner search then finds nothing bigger and runs off the front of the array. The partner search has the same trap: with < instead of <=, [1, 5, 1] swaps the pivot 1 with the last 1 and returns [1, 1, 5] instead of [5, 1, 1].
Sorting the tail instead of reversing it
nums[i + 1:] = sorted(nums[i + 1:])
Reverse nums[i + 1:] with two pointers.
The answer is correct, but sorting costs O(n log n) and Python's slice makes a copy, which breaks the O(1) memory rule. The tail is known to fall, so a reverse already sorts it in O(n).
Returning early when there is no pivot
if i < 0:
returnif i < 0:
nums.reverse()
returnThe largest order must wrap around to the smallest. [3, 2, 1] has to become [1, 2, 3]; returning early leaves it unchanged.
Edge cases
i starts at −1, so no pivot is searched and the reverse covers a single number. The array stays the same, which is correct: it is the only arrangement.
Complexity
Next Permutation FAQ
How do I get the previous permutation instead?
Flip every comparison: find the rightmost i with nums[i] > nums[i + 1], swap it with the largest tail value smaller than it (the first from the right with nums[j] < nums[i]), then reverse the tail. This matches C++'s std::prev_permutation.
How can I list all permutations in sorted order with this?
Sort the array, record it, then apply next permutation until the array is back in rising order. Repeated values are handled for free: each distinct arrangement appears exactly once, which recursive generators only manage with extra duplicate checks.
Why not generate every permutation and pick the one after the input?
There are up to n! permutations; for 100 numbers that is far more than any computer can list. The pivot method only reads the array a few times.