# [LeetCode] Next Permutation (Java)

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

## Analysis

At first, I tried several times but I always got a wrong answer. After searching on google, I found a very clean solution from isherlei.blogspot.com.

1. From right to left, find the first digit (PartitionNumber) which violate the increase trend.

2. From right to left, find the first digit which larger than PartitionNumber, call it ChangeNumber.

3. Swap the PartitionNumber and ChangeNumber.

4. Reverse all the digit on the right of partition index.

You can visit http://fisherlei.blogspot.com/2012/12/leetcode-next-permutation.html for details.

## Complexity

We only go through the array at most 3 times. So the complexity is $O(n)$.