31. Next Permutation
Description
Implement next permutation, which 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.
Constraints
1 <= nums.length <= 100
0 <= nums[i] <= 100
Approach

Links
GeeksforGeeks
YouTube
Examples
Input: nums = [1, 2, 3]
Output: [1, 3, 2]
Solutions
/**
* Time complexity :
* Space complexity :
*/
class Solution {
public void nextPermutation(int[] nums) {
if(nums == null || nums.length <= 1) return;
int n = nums.length;
int i = n-2;
while(i >= 0 && nums[i] >= nums[i+1]) {
i--;
}
if(i >= 0) {
int j = n-1;
while(j > 0 && nums[j] <= nums[i]) {
j--;
}
swap(nums, i, j);
}
reverse(nums, i+1, n-1);
}
private void swap(int[] nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
private void reverse(int[] nums, int left, int right) {
while(left < right) {
swap(nums, left, right);
left++;
right--;
}
}
}
Follow up
Last updated
Was this helpful?