Next Permutation

Pattern: Next permutation and rearrangement

medium

Find the first drop from the right, swap it with the smallest bigger value after it, and reverse the falling suffix. That is the next arrangement in dictionary order, done in place.

The problem

A permutation is one arrangement of an array's values. Change nums in place into the next larger arrangement in dictionary order. If it is already the largest, change it into the smallest one, sorted increasing. For example, [1, 2, 3] becomes [1, 3, 2], [3, 2, 1] becomes [1, 2, 3], and [1, 1, 5] becomes [1, 5, 1].

The function name nextPermutation matches LeetCode. Use the link above for the exact statement and limits. Only constant extra memory is allowed.

Think first

  • Which arrangement of a group of values is the largest? Which is the smallest?
  • To get the next one, should you change the left end or the right end of the array?
  • Once you know which index must grow, what should it grow to, and what should the rest become?

Hints

    Brute force, and why it fails

    List every permutation, sort them and pick the one after the current one: O(n! × n). This guide uses that on small tests to check the answers. The three-step method is O(n).

    The key insight

    The next arrangement keeps the longest possible prefix. Only the suffix from the first drop onwards changes, and it changes to the smallest arrangement that is still bigger.

    Dry run

    10 
    21i
    72 
    43 
    34 
    15 

    nums = [1, 2, 7, 4, 3, 1]. From the right, 1, 3, 4 and 7 keep rising. Then 2 is smaller than 7, so the drop is at i = 1.

    Step 1 of 4

    The plan

    i = n - 2
    while i >= 0 and nums[i] >= nums[i + 1]: i = i - 1
    if i >= 0:
        j = n - 1
        while nums[j] <= nums[i]: j = j - 1
        swap nums[i], nums[j]
    reverse nums from i + 1 to n - 1
    

    Complexity

    Time
    O(n)
    Space
    O(1)

    Each of the two scans and the reversal walks at most n values. Only a few indexes are stored.

    Edge cases

    • One value: nothing changes.
    • Fully falling, [3, 2, 1]: there is no drop, i ends at -1, and the whole array is reversed.
    • All equal, [2, 2, 2]: also no drop, and reversing changes nothing.
    • Repeats, [1, 5, 1]: the strict tests skip equal values, giving [5, 1, 1].
    I've built my logic, show the code

    Java

    class Solution {
        public void nextPermutation(int[] nums) {
            int n = nums.length;
            int i = n - 2;
            while (i >= 0 && nums[i] >= nums[i + 1]) i--;      // find the first drop from the right
            if (i >= 0) {
                int j = n - 1;
                while (nums[j] <= nums[i]) j--;                 // smallest value on the right that is bigger
                swap(nums, i, j);
            }
            for (int l = i + 1, r = n - 1; l < r; l++, r--) swap(nums, l, r);   // make the suffix increasing
        }
    
        private void swap(int[] a, int x, int y) {
            int t = a[x]; a[x] = a[y]; a[y] = t;
        }
    }

    C++

    class Solution {
    public:
        void nextPermutation(vector<int>& nums) {
            int n = static_cast<int>(nums.size());
            int i = n - 2;
            while (i >= 0 && nums[i] >= nums[i + 1]) i--;      // find the first drop from the right
            if (i >= 0) {
                int j = n - 1;
                while (nums[j] <= nums[i]) j--;                 // smallest value on the right that is bigger
                swap(nums[i], nums[j]);
            }
            reverse(nums.begin() + i + 1, nums.end());          // make the suffix increasing
        }
    };

    Python

    class Solution:
        def nextPermutation(self, nums: list[int]) -> None:
            n = len(nums)
            i = n - 2
            while i >= 0 and nums[i] >= nums[i + 1]:            # find the first drop from the right
                i -= 1
            if i >= 0:
                j = n - 1
                while nums[j] <= nums[i]:                       # smallest value on the right that is bigger
                    j -= 1
                nums[i], nums[j] = nums[j], nums[i]
            nums[i + 1:] = reversed(nums[i + 1:])               # make the suffix increasing

    Common mistakes

    • Using > instead of >= when looking for the drop, which stops at equal values and breaks [1, 5, 1].
    • Swapping with the first bigger value from the left instead of the right, which grows index i too much.
    • Sorting the suffix, which works but is slower than reversing it.

    Similar problems