Algo-Sim › Two Pointers
Next Permutation
Medium · Two Pointers · step through it in Java, Python and C++ on your own input
Find the rightmost ascent, swap it with the next larger value in the suffix, and reverse the suffix.
Problem
Rearrange the integer array nums in place into the next permutation in lexicographic order: the smallest arrangement that is strictly larger. If nums is already the largest arrangement, rearrange it into the smallest one (ascending). Use only O(1) extra memory.
Constraints
- 1 ≤ nums.length ≤ 100
- 0 ≤ nums[i] ≤ 100
- In place, O(1) extra memory
Edge cases to test
- The last permutation (descending): wrap to ascending
- Duplicates:
[1, 5, 1] - One element
Follow-up questions
- How do you get the previous permutation?
- Mirror the steps: find the rightmost descent, swap with the largest smaller value to its right, and reverse the suffix.
- How do you find the k-th permutation directly?
- Use the factorial number system: the first digit is
k / (n − 1)!, and so on: O(n²), or O(n log n) with a Fenwick tree (LC 60).
Solution
Java
public void nextPermutation(int[] nums) {
int i = nums.length - 2;
while (i >= 0 && nums[i] >= nums[i + 1]) i--;
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;
}
int lo = i + 1, hi = nums.length - 1;
while (lo < hi) {
int t = nums[lo]; nums[lo++] = nums[hi]; nums[hi--] = t;
}
}Python
def next_permutation(nums):
i = len(nums) - 2
while i >= 0 and nums[i] >= nums[i + 1]: i -= 1
if i >= 0:
j = len(nums) - 1
while nums[j] <= nums[i]: j -= 1
nums[i], nums[j] = nums[j], nums[i]
lo, hi = i + 1, len(nums) - 1
while lo < hi:
nums[lo], nums[hi] = nums[hi], nums[lo]
lo, hi = lo + 1, hi - 1C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
void nextPermutation(vector<int> &nums) {
int i = (int)nums.size() - 2;
while (i >= 0 && nums[i] >= nums[i + 1]) i--;
if (i >= 0) {
int j = (int)nums.size() - 1;
while (nums[j] <= nums[i]) j--;
swap(nums[i], nums[j]);
}
int lo = i + 1, hi = (int)nums.size() - 1;
while (lo < hi) {
swap(nums[lo++], nums[hi--]);
}
}
};
More Two Pointers problems
- Valid Palindrome (Easy)
- Valid Palindrome II (Easy)
- Two Sum II - Input Array Is Sorted (Medium)
- Remove Duplicates from Sorted Array (Easy)
- Move Zeroes (Easy)
- Container With Most Water (Medium)
- Trapping Rain Water (Hard)
- Sort Colors (Medium)
- Merge Sorted Array (Easy)
- Rotate Array (Medium)
- 3Sum (Medium)