DEV Community

Kaitian Xie
Kaitian Xie

Posted on • Edited on

2 1

LeetCode 31. Next Permutation

public class Solution {
    public void nextPermutation(int[] nums) {
        int i = nums.length - 2;
        while (i >= 0 && nums[i + 1] <= nums[i]) {
            i--;
        }
        if (i >= 0) {
            int j = nums.length - 1;
            while (j >= 0 && nums[j] <= nums[i]) {
                j--;
            }
            swap(nums, i, j);
        }
        reverse(nums, i + 1);
    }

    private void reverse(int[] nums, int start) {
        int i = start;
        int j = nums.length - 1;
        while (i < j) {
            swap(nums, i, j);
            i++;
            j--;
        }
    }

    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}

We iterate through nums from right to left to find the number nums[i] where the descending order occurs for the first time. Then we scan through the nums from right to i+1 to find a number that is greater nums[i] and swap the number with it. Finally, we reverse nums[i+1] ... nums[nums.length-1].

By doing so, we can guarantee that:

  1. The next permutation is always greater or equal to the current permutation (we assume the numbers in the current permutation are not sorted in descending order).
  2. There does not exist a permutation that is greater than the current permutation and smaller than the next permutation generated by the above code.
  3. If the numbers in the current permutation are already sorted in descending order (i.e. greatest possible value), the next permutation has the smallest value.

Time Complexity: O(n)

Extra Space: O(1)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay