Next Permutation

MediumArrays
Next
ArrayTwo Pointers

Rearrange the numbers into the next lexicographically greater permutation. If the arrangement is already the greatest possible, rearrange it into the lowest order (ascending).

Input

Line 1: n. Line 2: n integers (duplicates allowed).

Output

Print the next permutation on one line.

Constraints

1 <= n <= 10^5 0 <= each value <= 10^9

Example 1
Input
3
1 2 3
Output
1 3 2

The next arrangement after 1 2 3 is 1 3 2.

Example 2
Input
3
3 2 1
Output
1 2 3

3 2 1 is the largest, so wrap to ascending order.

Hints

Next Permutation - Medium Arrays Problem | Skill Shiksha