Description

A permutation of an array of integers is an arrangement of its members into a sequence. The next permutation of an array is the next lexicographically greater permutation. If no such arrangement exists, rearrange to the lowest possible order (sorted ascending). Modify the array in-place.

Examples

Input:nums = [1,2,3]
Output:[1,3,2]
Explanation:

The next permutation of [1,2,3] is [1,3,2].

Input:nums = [3,2,1]
Output:[1,2,3]
Explanation:

No next permutation exists, so reset to [1,2,3].

Input:nums = [2,3,1,4]
Output:[2,3,4,1]
Explanation:

To find the next permutation: 1) Find the rightmost character that is smaller than its next character - here it's '1' at index 2 (since 1 < 4). 2) Find the smallest character to the right of '1' that is larger than '1' - that's '4'. 3) Swap '1' and '4' to get [2,3,4,1]. 4) Since there's only one element after the swapped position, no reversal is needed. The result [2,3,4,1] is lexicographically the next permutation after [2,3,1,4].

Constraints

  • 1 ≤ nums.length ≤ 100
  • 0 ≤ nums[i] ≤ 100

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!