Next Permutation (LeetCode 31): Solution and Explanation

Medium
Array
Two Pointers

Rearrange an array of integers in place into the next permutation in lexicographic order, the smallest arrangement that is strictly larger than the current one. If the array is already the largest arrangement, wrap around to the smallest, which is ascending order.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The brute force idea is to generate every permutation in sorted order, find the current one, and return the one after it. That is O(n!) work and also needs memory for the list, so it is out. The real question is how to compute the next arrangement directly from the current one.

Think about how you count with digits: to get the next number, you change the rightmost digit that can still go up, and you reset everything after it to the smallest possible values. Permutations behave the same way. Look at the array from the right. As long as the values keep increasing as you move left, that suffix is in descending order, which means it is already the largest possible arrangement of those values, and nothing within it can be made bigger. The first position i where nums[i] < nums[i + 1] is the rightmost place that can be increased. Call it the pivot.

To increase the pivot as little as possible, swap it with the smallest value in the suffix that is still larger than it. Because the suffix is descending, that is the rightmost element greater than nums[i], found by scanning from the end. After the swap, the suffix is still in descending order, but now you want it as small as possible, which is ascending order. Reversing a descending sequence makes it ascending, so a simple reverse finishes the job in linear time. If no pivot exists, the entire array is descending, and reversing it gives the smallest permutation, which is exactly the required wraparound.

Approach: Pivot, swap, reverse suffix

  1. Start i at n - 2 and move left while nums[i] >= nums[i + 1]; this finds the pivot, the rightmost index with a larger neighbor to its right.
  2. If i >= 0, a pivot exists. Start j at n - 1 and move left while nums[j] <= nums[i] to find the rightmost value larger than the pivot.
  3. Swap nums[i] and nums[j], which increases the pivot by the smallest possible amount.
  4. Reverse the suffix from i + 1 to the end with two pointers, turning it from descending into ascending order.
  5. If no pivot was found, i is -1 and the reverse covers the whole array, producing the lowest permutation.

Step-by-step example

nums = [1, 3, 5, 4, 2]
  1. Starting at index 3, 4 is not less than 2, and at index 2, 5 is not less than 4. At index 1, 3 is less than 5, so the pivot is i = 1.
  2. Scanning from the right for a value larger than 3: 2 is not, but 4 at index 3 is, so j = 3.
  3. Swapping indices 1 and 3 gives [1, 4, 5, 3, 2]. The suffix after the pivot, [5, 3, 2], is still descending.
  4. Reversing that suffix gives [2, 3, 5], so the array becomes [1, 4, 2, 3, 5].
  5. That is the next permutation: no arrangement of these values lies strictly between 13542 and 14235.

Code: Python, Java, C++

1class Solution:
2    def nextPermutation(self, nums: List[int]) -> None:
3        n = len(nums)
4        i = n - 2
5
6        # Step 1: Find largest i where nums[i] < nums[i+1]
7        while i >= 0 and nums[i] >= nums[i + 1]:
8            i -= 1
9
10        if i >= 0:
11            # Step 2: Find largest j where nums[j] > nums[i]
12            j = n - 1
13            while nums[j] <= nums[i]:
14                j -= 1
15            # Step 3: Swap nums[i] and nums[j]
16            nums[i], nums[j] = nums[j], nums[i]
17
18        # Step 4: Reverse the suffix after i
19        left, right = i + 1, n - 1
20        while left < right:
21            nums[left], nums[right] = nums[right], nums[left]
22            left += 1
23            right -= 1

Time and space complexity

Time

O(n)

Finding the pivot, finding the swap target and reversing the suffix are each a single scan of at most n elements.

Space

O(1)

The array is modified in place, using only a few index variables.

Other approaches

Sort the suffix instead of reversing (time O(n log n), space O(1) to O(n) depending on the sort)

After the swap, sort the suffix in ascending order. It gives the same result and may feel more intuitive, but it costs O(n log n) and ignores the fact that the suffix is already in descending order.

Enumerate all permutations (time O(n! × n), space O(n! × n))

Generate permutations in lexicographic order and return the one after the current arrangement. It is useful only for checking answers on tiny inputs.

Common mistakes

  • Using a strict comparison when searching for the pivot. With duplicates, nums[i] > nums[i + 1] stops too early on equal values; the loop must skip while nums[i] >= nums[i + 1].
  • Swapping the pivot with the first larger element from the left of the suffix instead of the rightmost one. That picks a larger value than necessary and skips permutations.
  • Forgetting to reverse when there is no pivot. A fully descending array must wrap around to ascending order.
  • Reversing the whole array, or starting the reverse at i instead of i + 1, which moves the freshly swapped pivot.

Frequently asked questions

Why reverse the suffix instead of sorting it?

Before and after the swap, the suffix is in descending order. Reversing a descending sequence makes it ascending in O(n), which is the same result as sorting but faster.

What does Next Permutation do with the largest arrangement?

If the whole array is descending, there is no pivot, and the algorithm reverses the entire array, producing ascending order, the smallest permutation.

Does Next Permutation work with duplicate values?

Yes, as long as both scans use non-strict comparisons (>= for the pivot and <= for the swap target). That correctly skips equal values and avoids producing the same arrangement again.