Next Permutation
Medium
Topics
Rearrange nums into the lexicographically next greater permutation. If no greater permutation exists, rearrange to the lowest order (sorted ascending). Return the resulting array. Do it in-place with O(1) 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]
Constraints
- 1 <= nums.length <= 100
- 0 <= nums[i] <= 100
Editorial — intuition, approach, complexity and pitfalls
Intuition
Read the array from the right. A suffix that descends throughout is already the largest arrangement of its values, so no amount of rearranging inside it produces something bigger. Walk left until the first position i that is smaller than its right neighbour — that is the pivot, the only place where an increase is possible at all.
Bump the pivot as little as possible: swap it with the smallest value to its right that still exceeds it, which (because the suffix descends) is the rightmost such value. Then make the suffix as small as possible. It is descending, so reversing it is enough — no sort needed.
Approach
- Scan from the right for the first
iwithnums[i] < nums[i+1]. - If no such
iexists the whole array descends; skip to the reverse, which turns it into the ascending minimum. - Otherwise scan from the right for the first
jwithnums[j] > nums[i]and swap the two. - Reverse the suffix after
i, using two pointers.
Dry Run
nums = [1,3,5,4,2]
pivot scan from the right: first index smaller than its neighbour is i=1 (value 3)
suffix [5,4,2] is descending, so it is already maximal
rightmost value greater than 3 is at j=3 (value 4)
after swap [1,4,5,3,2]
after reversing the suffix [1,4,2,3,5]
answer [1,4,2,3,5]Complexity
- Time — O(n): three passes at worst, each over a slice of the array.
- Space — O(1) — but only if the suffix reverse uses two pointers. A slice assignment such as
nums[i+1:] = reversed(nums[i+1:])materialises a copy of the suffix and gives up the claim the problem explicitly asks for. The shown solution uses two pointers and says so in a comment.
Common Pitfalls
- Using
>instead of>=in the pivot scan. The scan then stops on a plateau of equal values, and the followingjscan walks off the front of the array — on[1,1]it raises an index error rather than returning[1,1]. - Using
<instead of<=in thejscan. On[1,5,1]that swaps the pivot with an equal value and returns[1,1,5]; the correct next permutation is[5,1,1]. - Sorting the suffix instead of reversing it. The result is right, but it is O(n log n) for work that a reversal does in O(n) — and it signals you have not noticed the suffix is already ordered.
- Forgetting the all-descending case. Here it falls out for free:
i = -1makesi + 1 = 0, so the reverse covers the whole array. - Generating permutations in order and picking the next one. That is factorial time for a problem with a three-step linear answer.
Full Solution — all languages
class Solution:
def nextPermutation(self, nums):
# 1. walk back to the first index that can be increased
i = len(nums) - 2
while i >= 0 and nums[i] >= nums[i + 1]:
i -= 1
# 2. swap it with the rightmost value greater than it
if i >= 0:
j = len(nums) - 1
while nums[j] <= nums[i]:
j -= 1
nums[i], nums[j] = nums[j], nums[i]
# 3. reverse the suffix, which is descending, to make it the smallest.
# Two pointers rather than nums[i+1:] = reversed(nums[i+1:]) -- the slice
# builds a copy of the suffix and gives up the O(1) space claim.
left, right = i + 1, len(nums) - 1
while left < right:
nums[left], nums[right] = nums[right], nums[left]
left += 1
right -= 1
return numsimport java.util.*;
class Solution {
public int[] nextPermutation(int[] nums) {
// 1. walk back to the first index that can be increased
int i = nums.length - 2;
while (i >= 0 && nums[i] >= nums[i + 1]) i--;
// 2. swap it with the rightmost value greater than it
if (i >= 0) {
int j = nums.length - 1;
while (nums[j] <= nums[i]) j--;
int t = nums[i]; nums[i] = nums[j]; nums[j] = t;
}
// 3. reverse the descending suffix in place
for (int left = i + 1, right = nums.length - 1; left < right; left++, right--) {
int t = nums[left]; nums[left] = nums[right]; nums[right] = t;
}
return nums;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> nextPermutation(vector<int>& nums) {
// 1. walk back to the first index that can be increased
int i = (int) nums.size() - 2;
while (i >= 0 && nums[i] >= nums[i + 1]) i--;
// 2. swap it with the rightmost value greater than it
if (i >= 0) {
int j = (int) nums.size() - 1;
while (nums[j] <= nums[i]) j--;
swap(nums[i], nums[j]);
}
// 3. reverse the descending suffix in place
for (int left = i + 1, right = (int) nums.size() - 1; left < right; left++, right--)
swap(nums[left], nums[right]);
return nums;
}
};/**
* @param {number[]} nums
* @return {number[]}
*/
var nextPermutation = function (nums) {
// 1. walk back to the first index that can be increased
let i = nums.length - 2;
while (i >= 0 && nums[i] >= nums[i + 1]) i--;
// 2. swap it with the rightmost value greater than it
if (i >= 0) {
let j = nums.length - 1;
while (nums[j] <= nums[i]) j--;
[nums[i], nums[j]] = [nums[j], nums[i]];
}
// 3. reverse the descending suffix in place
for (let left = i + 1, right = nums.length - 1; left < right; left++, right--) {
[nums[left], nums[right]] = [nums[right], nums[left]];
}
return nums;
};