Skip to content

Instantly share code, notes, and snippets.

@shalomsam
Created September 16, 2021 21:04
Show Gist options
  • Select an option

  • Save shalomsam/7adc8bd1b7d52f08e639af64327c5b87 to your computer and use it in GitHub Desktop.

Select an option

Save shalomsam/7adc8bd1b7d52f08e639af64327c5b87 to your computer and use it in GitHub Desktop.
Next Permutation

Next Permutation (Leetcode, Medium - Hard) ***

https://leetcode.com/problems/next-permutation/

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.

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]

Example 4:

Input: nums = [1] Output: [1]

Constraints:

1 <= nums.length <= 100 0 <= nums[i] <= 100

/**
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var swap = function(a,b,arr) {
let swp = arr[a];
arr[a] = arr[b];
arr[b] = swp;
}
var reverse = function(start, nums) {
let i = start;
let j = nums.length - 1;
while (i < j) {
swap(i, j, nums);
i++;
j--;
}
}
var nextPermutation = function(nums) {
let i = nums.length - 2;
while (i >=0 && nums[i+1] <= nums[i]) {
i--;
}
if (i >= 0) {
let j = nums.length - 1;
while (nums[j] <= nums[i]) {
j--;
}
swap(i, j, nums);
}
reverse(i+1,nums);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment