The first line contains a single integer ‘T’ representing the number of test cases.
The first line of each test case will contain an integer ‘N’ representing the length of the permutation.
The second line contains ‘N’ space-separated integers which are the elements of the permutation.
For each test case, print the elements of the lexicographically next greater permutation with a single space-separated. If lexicographically next greater permutation doesn’t exist, print the lexicographically smallest permutation.
Output for every test case will be printed in a separate line.
You do not need to print anything; It has already been taken care of.
1 <= T <= 50
1 <= N <= 10000
1 <= P[i] <= N
Time limit: 1 sec
The basic idea is to generate all the possible permutations of ‘N’ integers and find the lexicographically next greater permutation.
Steps are as follows:
The basic idea of this approach is to develop a greedy algorithm to find the lexicographically next greater permutation.
First of all, note that a permutation of integers which is sorted in descending order, will not have any lexicographically greater permutation. For example, no next permutation will be possible for [4, 3, 2, 1].
Now, consider two elements in the given permutation, P[i] and P[j] such that i < j. If P[i] < P[j], we can easily swap the ith and the jth element to generate a permutation which will be necessarily greater than the previous one. But in order to find the smallest among all of them we will have to choose (i, j) such that the ith element will be farthest from the front and if there are multiple options for the jth element, we will choose the smallest one. Why? Since we are considering the lexicographical ordering, a positive change in the element closer to front will generate a larger number than the other one. For example, consider [3, 4, 1, 2], if we choose i = 0, j = 1, then we will get next permutation [4, 3, 1, 2] and if we choose i = 2, j = 3, then we will get a lexicographically smaller permutation [3, 4, 2, 1]. Therefore, we should choose ‘i’ as large as possible.
Now, consider the following steps:
Merge Two Sorted Arrays Without Extra Space
Merge Two Sorted Arrays Without Extra Space
Ninja And The Strictly Increasing Array
Maximize
Negative To The End
Find Duplicate in Array