sagelearnai

Next Permutation

Difficulty: Medium · Pattern: Two Pointers · LeetCode #31

Rearrange nums in place into the next lexicographically greater permutation. If none exists (the array is in descending order), rearrange it into the lowest order (ascending). Use O(1) extra memory. Return nothing.

Examples

text
[1, 2, 3]  →  [1, 3, 2]
[3, 2, 1]  →  [1, 2, 3]
[1, 1, 5]  →  [1, 5, 1]
[1, 3, 2]  →  [2, 1, 3]

Hints

  1. Scan from the right for the first index i with nums[i] < nums[i+1]. Everything after i is non-increasing.
  2. Swap nums[i] with the smallest element to its right that is larger than it.
  3. Then make the suffix as small as possible.

Approach

  1. Find the rightmost i with nums[i] < nums[i+1]. If there's none, reverse the whole array (it was the last permutation).
  2. Find the rightmost j > i with nums[j] > nums[i], and swap them.
  3. Reverse nums[i+1:]. The suffix was non-increasing, so reversing makes it the smallest arrangement.

Complexity

Time: O(n). Space: O(1).

Python solution
def nextPermutation(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]
    l, r = i + 1, len(nums) - 1
    while l < r:
        nums[l], nums[r] = nums[r], nums[l]
        l += 1; r -= 1
JavaScript solution
function nextPermutation(nums) {
  let i = nums.length - 2;
  while (i >= 0 && nums[i] >= nums[i + 1]) i--;
  if (i >= 0) {
    let j = nums.length - 1;
    while (nums[j] <= nums[i]) j--;
    [nums[i], nums[j]] = [nums[j], nums[i]];
  }
  for (let l = i + 1, r = nums.length - 1; l < r; l++, r--) [nums[l], nums[r]] = [nums[r], nums[l]];
}