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

Edge cases to test

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 - 1

C++

#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