You have been given a string ‘S’. You need to return the lexicographically smallest subsequence of ‘S’ that contains all the distinct characters of ‘S’ exactly once. Return the string as mentioned above.
A string is a subsequence of a given string, that is generated by deleting some character of a given string without changing its order.
Example:Let S = “ababc”. The lexicographically smallest subsequence containing all the distinct characters of strings is “abc”.
Note:
Strings consist of only lowercase characters.
You do not need to print anything; it has already been taken care of. Just implement the function.
The first line contains a single integer ‘T’ representing the number of test cases.
The first line of each test case contains a single integer ‘N’ denoting the length of the string ‘S’.
The next line of the test case contains the string ‘S’.
Output Format:
For each test case return the lexicographically smallest subsequence of ‘S’ that contains all the distinct characters of ‘S’ exactly once.
1 <= T <= 10
1 <= N <= 1000
Time Limit: 1sec
2
7
aababcb
5
bcabb
abc
bca
Test case 1:
The lexicographically smallest subsequence contains all the distinct characters of strings is “abc”.
Therefore the answer is “abc”.
Test case 2:
The lexicographically smallest subsequence contains all the distinct characters of strings is “bca”.
Therefore the answer is “bca”.
2
7
gggjhhh
8
laughhgu
gjh
laghu
Brute Force.
Iterate over all the subsequences of string ‘S’:-
O(N * 2 ^ N), where ‘N’ denotes the length of the string.
As we are iterating over all the subsequences of string and for each subsequence we are iterating ‘S’ which is of length ‘N’.
O(N), where ‘N’ denotes the length of the string.
As we recurse we build a string of length ‘N’.