The problem “Next Permutation” asks you to implement a function that rearranges numbers into the lexicographically next greater permutation of numbers. If such an arrangement is not possible, it must rearrange it as the lowest possible order (i.e., sorted in ascending order). The replacement must be in place and use only constant extra memory.
Input: nums = [1,2,3]
Output: [1,3,2]
Input: nums = [3,2,1]
Output: [1,2,3]
Input: nums = [1,1,5]
Output: [1,5,1]
-1000
to 1000
.Here is a detailed step-by-step strategy to solve the problem:
nums[i] < nums[i + 1]
. Let this index be i
.nums[i]
from the right-hand side:
j
such that nums[j] > nums[i]
.Swap the values at indices i
and j
.
i+1
to the end of the array:
i
exists (i.e., the array is in descending order), reverse the entire array to get the smallest permutation.#include <vector>
#include <algorithm>
void nextPermutation(std::vector<int>& nums) {
int n = nums.size();
int i = n - 2;
// Step 1: Find first descending pair from the right end.
while (i >= 0 && nums[i] >= nums[i + 1]) {
i--;
}
if (i >= 0) {
// Step 2: Find the smallest number greater than nums[i] from the right end.
int j = n - 1;
while (nums[j] <= nums[i]) {
j--;
}
// Step 3: Swap nums[i] and nums[j].
std::swap(nums[i], nums[j]);
}
// Step 4: Reverse the part from i+1 to the end of the array.
std::reverse(nums.begin() + i + 1, nums.end());
}
nums[i]
: O(n) in the worst case.Thus, the overall time complexity is O(n), which is efficient for the constraints given.
This solution uses only constant extra space, thus meeting the in-place requirement.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?