All problems

Problem 208

Next Permutation

Medium · 20 pts · Array, Two Pointers

Problem

You are given an array of N integers. Rearrange it into the next permutation in lexicographic (dictionary) order: the smallest arrangement of the same values that is strictly larger than the current one. If the array is already the largest possible arrangement (sorted in descending order), rearrange it into the smallest one (sorted in ascending order). The standard steps: find the rightmost index i with A[i] < A[i + 1]. If there is none, reverse the whole array. Otherwise find the rightmost element larger than A[i], swap them, and reverse everything after position i.

Input

First line: integer N. Second line: N space-separated integers.

Output

Print the resulting array, space-separated.

Constraints

1 <= N <= 100000; 0 <= A[i] <= 100

Example input

3
1 2 3

Example output

1 3 2

Explanation

The arrangements of 1 2 3 in order are 1 2 3, 1 3 2, 2 1 3, and so on. The one right after 1 2 3 is 1 3 2.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Subarrays Divisible by K Next: Kth Missing Positive Number