
The string ‘STR’ contains only lowercase alphabet characters.
If ‘STR’ = “aaadbbcc” and ‘D’ = 2.
Then one of the possible solution is “abacabcd”.
The first line contains a single integer ‘T’ representing the number of test cases.
The first line of each test case will contain two single space-separated integers ‘N’ and ‘D’ which denote the size of the ‘STR’ and the distance such that the same characters are present at least ‘D’ distance from each other, respectively.
The next line of each test case contains the string ‘STR’.
For each test case, print "true" if it is possible to rearrange the string ‘STR’, otherwise, print "false" without quotes.
Output for every test case will be printed in a separate line.
You don’t need to print anything; it has already been taken care of. Just implement the given function.
1 <= ‘T’ <= 50
1 <= ‘N’ <= 10000
1 <= ‘D’ <= 26
‘STR’ = {a - z}
Time limit: 1 sec
The basic idea is to first store all the characters of this ‘STR’ in a HashMap. Then iterate over this HashMap, store these key-value pairs in a max-heap and sort according to the frequency of these characters.
Then Iterate over this heap and greedily remove the top different ‘D’ characters from the heap and store them in a resultant string.