Next Permutation solution explained
To get the next permutation in place, scan from the right for the first index i where nums[i] is smaller than nums[i + 1]; that is the pivot. Swap it with the rightmost value to its right that is larger than it, then reverse everything after index i. If no pivot exists, the array is in its last order, so reversing the whole array wraps it around to the first. It runs in O(n) time and O(1) extra space.
By Evin JohnPublished 7 min read
Restating the task
Treat the array as one arrangement among all orderings of its values, sorted in dictionary order, the way words are ordered by their first letter, then their second, and so on. Change the array in place into the arrangement that comes right after it. If it is already the last arrangement, change it into the first one, which is the values in ascending order. Values may repeat.
| Now | Next | What happened |
|---|---|---|
| [2, 5, 4, 1] | [4, 1, 2, 5] | Pivot 2; next larger in the tail is 4; tail reversed |
| [1, 3, 2] | [2, 1, 3] | Pivot 1; swap with 2; reverse [3, 1] |
| [6, 4, 3] | [3, 4, 6] | No pivot, so wrap to ascending |
| [2, 2, 7] | [2, 7, 2] | Pivot is the second 2 |
| [3, 1, 1] | [1, 1, 3] | Already the last arrangement |
| [7] | [7] | Only one arrangement exists |
Why it is asked
Few people derive this algorithm cold, so interviewers mainly want to see you reason about orderings: which part of the array can change as little as possible, and why. A candidate who can explain why the tail is descending and why reversing it gives the smallest tail shows real understanding. Candidates who only memorized the three steps often break on repeated values, which is a good test of the comparison signs.
Follow-ups
- Previous permutation. Mirror every comparison: find the first index from the right where nums[i] is larger than the next value, swap with the rightmost smaller value, reverse the tail.
- Next larger number with the same digits. Apply this to the digit list, and return -1 or a sentinel when no pivot exists or the result overflows.
- List all permutations in order. Start from the sorted array and call next permutation until it wraps, which also handles repeated values without a set.
- The kth permutation. Calling next k times is O(n × k); the factorial number system jumps straight there.
Brute force: list every ordering
Generate every distinct ordering, sort them, find the current one, and take the next, wrapping to the first at the end. It is obviously correct and useless beyond about ten values, since there are up to n! orderings. Still, it is the right tool for testing the real solution on small random inputs.
from itertools import permutations
def next_permutation_brute(nums):
# Every distinct arrangement, sorted; pick the one after the current, or wrap.
orders = sorted(set(permutations(nums)))
i = orders.index(tuple(nums))
nums[:] = orders[(i + 1) % len(orders)]The linear scan
To make the smallest possible increase, change the array as far to the right as you can. Scan from the right while values are not increasing; the tail you pass is in descending order, which is already its largest arrangement, so no change inside it can help. The first index i where nums[i] is smaller than nums[i + 1] is the pivot: the rightmost position that can grow. Replace it with the smallest value in the tail that is larger than it, which, because the tail is descending, is the rightmost such value. After the swap, the tail is still descending, so reverse it to make it ascending, its smallest arrangement.
def next_permutation(nums):
n = len(nums)
# 1. Find the pivot: the rightmost index whose value is smaller than the next one.
i = n - 2
while i >= 0 and nums[i] >= nums[i + 1]:
i -= 1
if i >= 0:
# 2. Swap it with the rightmost value to its right that is larger than it.
j = n - 1
while nums[j] <= nums[i]:
j -= 1
nums[i], nums[j] = nums[j], nums[i]
# 3. The suffix after i is in descending order; reverse it to make it ascending.
lo, hi = i + 1, n - 1
while lo < hi:
nums[lo], nums[hi] = nums[hi], nums[lo]
lo += 1
hi -= 1Walk through [2, 5, 4, 1]. From the right, 4 > 1 and 5 > 4, but 2 < 5, so the pivot is index 0 with value 2. In the tail [5, 4, 1], the rightmost value larger than 2 is 4. Swapping gives [4, 5, 2, 1], and reversing the tail [5, 2, 1] gives [4, 1, 2, 5]. When no pivot is found, i ends at -1 and the reversal covers the whole array.
#include <algorithm>
#include <utility>
#include <vector>
void nextPermutation(std::vector<int>& nums) {
int n = static_cast<int>(nums.size());
if (n < 2) return; // nothing to rearrange
int i = n - 2;
while (i >= 0 && nums[i] >= nums[i + 1]) --i; // find the pivot
if (i >= 0) {
int j = n - 1;
while (nums[j] <= nums[i]) --j; // smallest larger value on the right
std::swap(nums[i], nums[j]);
}
std::reverse(nums.begin() + (i + 1), nums.end()); // descending tail becomes ascending
}The early return for fewer than two values is not decoration. Without it, an empty vector gives i = -2 and the reverse call would start before the beginning of the vector, which is undefined behaviour. The comparisons use >= and <= on purpose. With a strict sign in the pivot scan, [3, 3, 1] picks the wrong pivot and the code fails; with a strict sign in the swap scan, [1, 5, 1] swaps two equal 1s and returns [1, 1, 5] instead of [5, 1, 1]. In real C++ code, std::next_permutation does all of this and returns false when it wraps.
Complexity
| Approach | Time | Extra space |
|---|---|---|
| List and sort all orderings | At least O(n! × n) | O(n! × n) |
| Pivot, swap, reverse | O(n) | O(1) |
Edge cases
- Empty array or a single value: nothing changes.
- Descending order: wrap to ascending.
- Strictly ascending order: only the last two values swap.
- Repeated values, especially right around the pivot.
- Two values, where the result is either a swap or the same pair.
Mistakes
- Scanning for the pivot from the left.
- Swapping the pivot with the largest value in the tail rather than the smallest larger one.
- Sorting the tail instead of reversing it. It is correct but O(n log n), and it shows you missed that the tail is already descending.
- Using strict comparisons and failing on repeats such as [1, 5, 1].
- Forgetting the wrap-around case and leaving a descending array untouched.
How to present it
Fictional example
- Candidate
- To get the next larger order, I want to change the array as far right as possible.
- Candidate
- From the right, while values keep going up as I move left, that tail is descending, which is already its largest order. So the first spot where a value is smaller than the one after it is where things must change.
- Candidate
- I swap that pivot with the smallest bigger value in the tail. Since the tail is descending, that's the rightmost one bigger than the pivot. The tail stays descending, so I reverse it to make it as small as possible.
- Candidate
- If there's no pivot, the whole array is descending and I just reverse it. Linear time, constant space.
Related problems
Permutations lists every ordering with backtracking, and you can produce the same list in order by calling this repeatedly. Reversing part of an array is also the key move in Rotate Array. Sort Colors and Subarray Sum Equals K continue with array problems of a different kind.
How Natively can help
Next Permutation is a problem where reading a correct solution is not the same as understanding it. Natively can read the problem from a screenshot on Mac or Windows and walk through the pivot, swap and reverse with code. Comparing that walkthrough with your own reasoning shows which step you skipped. Practicing the explanation aloud with Natively transcribing helps you hear whether it makes sense. See Natively for coding interviews.
Questions people ask
How does the next permutation algorithm work?
Find the rightmost index i with nums[i] < nums[i + 1]. Swap nums[i] with the rightmost value after it that is larger, then reverse everything after i. If there is no such i, reverse the whole array.
Why do you reverse the suffix in Next Permutation?
The part after the pivot is in descending order, its largest arrangement. After the swap it is still descending, and reversing it gives its smallest arrangement, which makes the overall increase as small as possible.
What is the time complexity of Next Permutation?
O(n) time and O(1) extra space. Each of the three steps scans at most the whole array once.
What happens when the array is already the last permutation?
No pivot exists because the array is in descending order. Reversing the whole array returns the first permutation, the values in ascending order.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
