You are given a string βSβ of length βNβ and a positive integer βKβ. You can perform the following operation any number of times on βSβ.
In each operation, you can delete one of the first βKβ characters of βSβ and append it at the end of the βSβ.
You have to find the lexicographically smallest string you can obtain by performing any number of operations.
Note:
String βpβ is lexicographically smaller than string βqβ, if βpβ is a prefix of βqβ, is not equal to βqβ or there exists βiβ, such that βp[i]β < ββq[i]β and for all βjβ β<β βiβ it is satisfied that βp[j]β = ββq[j]β.
The first line contains a single integer βTβ representing the number of test cases.
The first line of each test case will contain two space-separated integers βNβ and βKβ which denotes the length of βSβ and integer βKβ.
The second line of each test case will contain a single string βSβ.
Output Format:
For each test case, return the lexicographically smallest string obtained by performing any number of operations on βSβ.
Note:
You donβt need to print anything; it has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 10^3
1<= K <= N
S[ i ] belongs to {a to z}
Time limit: 1 sec
2
5 1
acbaa
3 2
onm
aaacb
mno
In the first test case,
In the first move we will delete βaβ from the beginning and put it at the end, βSβ = βcbaaaβ.
In the second move we will delete βcβ from the beginning and put it at the end, βSβ = βbaaacβ.
In the third move we will delete βbβ from the beginning and put it at the end, βSβ = βaaacbβ.
For the second test case,
In the first move we will delete βnβ and put it at the end, βSβ = βomnβ.
In the second move we will delete βoβ from the beginning and put it at the end, βSβ = βmnoβ.
2
1 1
t
12 12
codingninjas
t
acdgiijnnnos
Can we obtain all the possible permutations?
For the value of the βKβ > 1 it is possible to obtain any permutation of the string βSβ. Considering two characters at index βiβ and βi + 1β we will prove that it is possible to swap them.
After this operation, two characters are swapped.
This way by swapping any two consecutive characters we can obtain any permutation.
For βKβ = 1, after any number of operations, we will get one of its circular rotations.
Eg for βabcdβ : βabcdβ, βbcdaβ, βcdabβ, βdabcβ are possible.
We will compare all the circular rotations and pick the smallest of all as our answer.
The steps are as follows:
O(N ^ 2), where βNβ is the length of the string βSβ.
When βKβ = 1, we will compare βNβ strings of length βNβ to get the lowest possible string. So the overall time complexity will be O(N ^ 2).
O(N), where βNβthe length of the string βSβ.
The space required to store the final result βresβ will be O (N). So the overall space complexity will be O(N)