#K80967. Next Permutation

    ID: 35648 Type: Default 1000ms 256MiB

Next Permutation

Next Permutation

You are given an array of integers. Your task is to rearrange the array into its lexicographically next greater permutation of numbers. If such an arrangement is not possible, then rearrange it as the lowest possible order (i.e., sorted in ascending order).

To explain the algorithm in brief, you can follow these steps:

  1. Find the largest index \( k \) such that \( nums[k] < nums[k+1] \). If no such index exists, reverse the array and finish.
  2. Find the largest index \( l \) greater than \( k \) such that \( nums[k] < nums[l] \).
  3. Swap \( nums[k] \) and \( nums[l] \).
  4. Reverse the sub-array from \( nums[k+1] \) to the end of the array.
This algorithm guarantees that we obtain the next permutation in lexicographical order using only constant extra memory.

inputFormat

Input is provided as a single line from standard input (stdin) containing space-separated integers. These integers represent the array for which you need to find the next permutation.

outputFormat

Output the rearranged array in a single line to standard output (stdout) as space-separated integers. This output should represent the next lexicographical permutation of the input array.## sample

1 2 3
1 3 2

</p>