# 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**

*


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://code-snippets.hbamithkumara.com/leetcode/problems/1-100/next-permutation.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
