31. Next Permutation
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to find the next lexicographically greater permutation of a given array of integers. If the array is already the largest permutation (i.e., sorted in descending order), we need to rearrange it to the smallest possible permutation (i.e., sorted in ascending order). The modification must be done in-place, using only constant extra space.
Solution
Next Permutation in Python
class Solution:
def nextPermutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
n = len(nums)
if n <= 1:
return
# Step 1: Find the first element from the right that is smaller than the element to its right.
# This is the pivot 'k'.
k = -1
for i in range(n - 2, -1, -1):
if nums[i] < nums[i + 1]:
k = i
break
# If no such pivot exists, the array is sorted in descending order.
# This is the last permutation. Reverse it to get the first permutation.
if k == -1:
nums.reverse()
return
# Step 2: Find the smallest element to the right of k that is greater than nums[k].
# This is the element to swap with, 'l'.
l = -1
for i in range(n - 1, k, -1):
if nums[i] > nums[k]:
l = i
break
# Step 3: Swap the elements at k and l.
nums[k], nums[l] = nums[l], nums[k]
# Step 4: Reverse the sub-array to the right of k.
# This can be done by reversing the slice from k+1 to the end.
left, right = k + 1, n - 1
while left < right:
nums[left], nums[right] = nums[right], nums[left]
left += 1
right -= 1
Next Permutation in Java
class Solution {
public void nextPermutation(int[] nums) {
int n = nums.length;
// Step 1: Find the first decreasing element from the right
// This is the pivot 'k'
int k = -1;
for (int i = n - 2; i >= 0; i--) {
if (nums[i] < nums[i + 1]) {
k = i;
break;
}
}
// If no such element is found, the permutation is the last permutation.
// Reverse the array to get the first permutation (sorted in ascending order).
if (k == -1) {
reverse(nums, 0, n - 1);
return;
}
// Step 2: Find the smallest element to the right of k that is greater than nums[k]
// This is the element to swap with, 'l'
int l = -1;
for (int i = n - 1; i > k; i--) {
if (nums[i] > nums[k]) {
l = i;
break;
}
}
// Step 3: Swap nums[k] and nums[l]
swap(nums, k, l);
// Step 4: Reverse the sub-array to the right of k
reverse(nums, k + 1, n - 1);
}
// Helper function to swap two elements in an array
private void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
// Helper function to reverse a sub-array
private void reverse(int[] nums, int start, int end) {
while (start < end) {
swap(nums, start, end);
start++;
end--;
}
}
}
Next Permutation in C++
class Solution {
public:
void nextPermutation(vector<int>& nums) {
int n = nums.size();
// Step 1: Find the first decreasing element from the right
int k = -1;
for (int i = n - 2; i >= 0; i--) {
if (nums[i] < nums[i + 1]) {
k = i;
break;
}
}
// If no such element is found, the permutation is the last permutation.
// Reverse the array to get the first permutation.
if (k == -1) {
reverse(nums.begin(), nums.end());
return;
}
// Step 2: Find the smallest element to the right of k that is greater than nums[k]
int l = -1;
for (int i = n - 1; i > k; i--) {
if (nums[i] > nums[k]) {
l = i;
break;
}
}
// Step 3: Swap nums[k] and nums[l]
swap(nums[k], nums[l]);
// Step 4: Reverse the sub-array to the right of k
reverse(nums.begin() + k + 1, nums.end());
}
};
Next Permutation in TypeScript
/**
Do not return anything, modify nums in-place instead.
*/
function nextPermutation(nums: number[]): void {
const n = nums.length;
if (n <= 1) {
return;
}
// Helper function to swap two elements
const swap = (i: number, j: number): void => {
[nums[i], nums[j]] = [nums[j], nums[i]];
};
// Helper function to reverse a sub-array
const reverse = (start: number): void => {
let left = start;
let right = n - 1;
while (left < right) {
swap(left, right);
left++;
right--;
}
};
// Step 1: Find the pivot k
let k = -1;
for (let i = n - 2; i >= 0; i--) {
if (nums[i] < nums[i + 1]) {
k = i;
break;
}
}
// If no pivot, array is in descending order, reverse it
if (k === -1) {
reverse(0);
return;
}
// Step 2: Find the element l to swap with k
let l = -1;
for (let i = n - 1; i > k; i--) {
if (nums[i] > nums[k]) {
l = i;
break;
}
}
// Step 3: Swap elements at k and l
swap(k, l);
// Step 4: Reverse the sub-array from k+1 to the end
reverse(k + 1);
};
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.