> For the complete documentation index, see [llms.txt](https://protegejj.gitbook.io/algorithm-practice/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://protegejj.gitbook.io/algorithm-practice/google/31-next-permutation.md).

# 31 Next Permutation

## 31. [Next Permutation](https://leetcode.com/problems/next-permutation/description/)

## 1. Question

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

The replacement must be in-place, do not allocate extra memory.

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.\
`1,2,3`→`1,3,2`\
`3,2,1`→`1,2,3`\
`1,1,5`→`1,5,1`

## 2. Implementation

```java
class Solution {
    public void nextPermutation(int[] nums) {
        int i = nums.length - 1;
        while (i > 0 && nums[i - 1] >= nums[i]) {
            --i;
        }

        if (i > 0) {
            int j = nums.length - 1;

            while (j >= i && nums[i - 1] >= nums[j]) {
                --j;
            }

            swap(nums, i - 1, j);
        }
        reverse(nums, i, nums.length - 1);
    }

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

    public void reverse(int[] nums, int start, int end) {
        while (start < end) {
            swap(nums, start , end);
            ++start;
            --end;
        }
    }
}
```

## 3. Time & Space Complexity

时间复杂度O(n), 空间复杂度O(1)
