> For the complete documentation index, see [llms.txt](https://code-snippets.hbamithkumara.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://code-snippets.hbamithkumara.com/leetcode/problems/1-100/next-permutation.md).

# 31. Next Permutation

### Description

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

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

The replacement must be [**in place**](http://en.wikipedia.org/wiki/In-place_algorithm) and use only constant extra memory.

### Constraints

* `1 <= nums.length <= 100`
* `0 <= nums[i] <= 100`

### Approach

<div align="left"><img src="/files/-MK9RvyeZY4---X6CIt9" alt=""></div>

### Links

* GeeksforGeeks
* [Leetcode](https://leetcode.com/problems/next-permutation/)
* [ProgramCreek](https://www.programcreek.com/2014/06/leetcode-next-permutation-java/)
* YouTube

### **Examples**

{% tabs %}
{% tab title="Example 1" %}
**Input:** nums = \[1, 2, 3]

**Output:** \[1, 3, 2]
{% endtab %}

{% tab title="Example 2" %}
**Input:** nums = \[3, 2, 1]

**Output:** \[1, 2, 3]
{% endtab %}

{% tab title="Example 3" %}
**Input:** nums = \[1, 1, 5]

**Output:** \[1, 5, 1]
{% endtab %}

{% tab title="Example 4" %}
**Input:** nums = \[1]

**Output:** \[1]
{% endtab %}
{% endtabs %}

### **Solutions**

{% tabs %}
{% tab title="Solution 1" %}

```java
/**
 * Time complexity : 
 * Space complexity : 
 */

class Solution {
    public void nextPermutation(int[] nums) {
        if(nums == null || nums.length <= 1) return;
        
        int n = nums.length;
        int i = n-2;
        
        while(i >= 0 && nums[i] >= nums[i+1]) {
            i--;
        }
        
        if(i >= 0) {
            int j = n-1;
            while(j > 0 && nums[j] <= nums[i]) {
                j--;
            }
            swap(nums, i, j);
        }
        
        reverse(nums, i+1, n-1);
    }
    
    private void swap(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
    
    private void reverse(int[] nums, int left, int right) {
        while(left < right) {
            swap(nums, left, right);
            left++;
            right--;
        }
    }
}
```

{% endtab %}
{% endtabs %}

### **Follow up**

*
