LeetCode #31 Medium

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.

Constraints
  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 100
arraytwo-pointers
Open on LeetCode ↗
02

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.

How to spot this pattern

"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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def nextPermutation(self, nums):
▶3 i = len(nums) - 2
▶4 while i >= 0 and nums[i] >= nums[i + 1]:
▶5 i -= 1
▶6 if i >= 0:
▶7 j = len(nums) - 1
▶8 while nums[j] <= nums[i]:
▶9 j -= 1
▶10 nums[i], nums[j] = nums[j], nums[i]
▶11 left, right = i + 1, len(nums) - 1
▶12 while left < right:
▶13 nums[left], nums[right] = nums[right], nums[left]
▶14 left += 1
▶15 right -= 1
158476531tailscan from the right for the first drop
nums[1, 5, 8, 4, 7, 6, 5, 3, 1]
The next permutation changes as little as possible at the right end, so the scan starts there. On its own the last number is a falling tail of length 1.
15847653check1falling tail3 is not smaller than 1 → the tail grows
i7
3 ≥ 1, so the numbers from index 7 to the end still never rise. A tail that only falls is already the largest arrangement of its numbers, so nothing inside it can be bumped up.
1584765check31falling tail5 is not smaller than 3 → the tail grows
i6
5 ≥ 3, so the numbers from index 6 to the end still never rise. A tail that only falls is already the largest arrangement of its numbers, so nothing inside it can be bumped up.
158476check531falling tail6 is not smaller than 5 → the tail grows
i5
6 ≥ 5, so the numbers from index 5 to the end still never rise. A tail that only falls is already the largest arrangement of its numbers, so nothing inside it can be bumped up.
15847check6531falling tail7 is not smaller than 6 → the tail grows
i4
7 ≥ 6, so the numbers from index 4 to the end still never rise. A tail that only falls is already the largest arrangement of its numbers, so nothing inside it can be bumped up.
1584pivot76531falling tail4 is smaller than 7 → pivot at index 3
i3
Here the sequence rises (4 < 7). Index 3 is the rightmost place that can grow, so it is the pivot: everything to its left stays, and the pivot must become slightly larger.
1584pivot76531checkfalling tail1 is not bigger than 4 → move left
j8
1 ≤ 4, so putting it in the pivot's place would not make the array bigger. The tail falls from left to right, so the first number from the right that beats 4 is the smallest one that does.
1584pivot7653check1falling tail3 is not bigger than 4 → move left
j7
3 ≤ 4, so putting it in the pivot's place would not make the array bigger. The tail falls from left to right, so the first number from the right that beats 4 is the smallest one that does.
1584pivot765partner31falling tail5 is bigger than 4 → swap partner at index 6
j6
5 is the smallest number in the tail that is larger than 4. Putting it at the pivot gives the smallest possible increase at that position.
158576431still fallingswap 4 and 5
nums[1, 5, 8, 5, 7, 6, 4, 3, 1]
After the swap, index 3 holds 5. The tail still falls: 4 is smaller than the numbers to the left of its new spot and at least as big as those to the right, so the tail is still the largest order of its numbers.
158516437reversing the tailreverse the tail: swap 7 and 1
left, right4, 8
nums[1, 5, 8, 5, 1, 6, 4, 3, 7]
The tail must now be its smallest order, rising from left to right. It falls, so reversing it is enough: swap the two ends and step both inward.
158513467reversing the tailreverse the tail: swap 6 and 3
left, right5, 7
nums[1, 5, 8, 5, 1, 3, 4, 6, 7]
The tail must now be its smallest order, rising from left to right. It falls, so reversing it is enough: swap the two ends and step both inward.
158513467answer: 1, 5, 8, 5, 1, 3, 4, 6, 7
nums[1, 5, 8, 5, 1, 3, 4, 6, 7]
The prefix is unchanged, the pivot grew by the smallest step available, and the tail is in its smallest order. No arrangement fits between the old array and this one.
05

Common pitfalls

Strict comparisons with repeated values

✗ Wrong
while i >= 0 and nums[i] > nums[i + 1]:
    i -= 1
✓ Right
while i >= 0 and nums[i] >= nums[i + 1]:
    i -= 1

Equal 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

✗ Wrong
nums[i + 1:] = sorted(nums[i + 1:])
✓ Right
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

✗ Wrong
if i < 0:
    return
✓ Right
if i < 0:
    nums.reverse()
    return

The largest order must wrap around to the smallest. [3, 2, 1] has to become [1, 2, 3]; returning early leaves it unchanged.

06

Edge cases

One element, such as [7]

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.

07

Complexity

Time
O(n)
Space
O(1)
The pivot scan, the partner scan and the reverse each touch every index at most once. Only a few indices are stored.
08

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.