Given a string “STR”, you need to return all the possible non-empty subsequences with distinct characters. You can return the strings in any order.
Note:If the same string can be generated multiple times, return them multiple times.
A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
For eg. Let the input string be 'cbc'. Then all the subsequences with distinct characters will be - ['c', 'bc', 'c', 'cb', 'b'].
The first line of input contains an integer ‘T’ denoting the number of test cases to run. Then the test case follows.
The first and the only line of each test case contains the string 'STR'.
Output Format :
For each test case, print all the substrings with distinct characters.
Output for each test case will be printed in a new line.
Note:
You do not need to print anything; it has already been taken care of. Just implement the given functions.
1 <= T <= 100
1 <= |STR| <= 15
Where |STR| denotes the length of “STR”
String “STR” will only consist of lowercase English Alphabets.
Time Limit: 1 sec
2
aba
xyz
a
a
ab
b
ba
x
xy
xyz
xz
y
yz
z
In the first case,
The only valid sequences of length one are “a” -> 2 times, “b” -> 1 time. For length two, “ab” and “ba” both occur only once. There is no valid sequence possible for length three as the only subsequence of length three is “aba” which is not valid. Hence, the answer is the list of all 5 subsequences created.
In the second case,
The only valid sequences of length one are “x”, “y” and “z”. For length two, “xy”, “xz” and “yz” are valid. For length three “xyz” is valid. Note that repetition is not possible in this case as there are no characters that occur multiple times. Hence, the answer is the list of all 7 subsequences created.
2
abca
zzz
a
a
ab
abc
ac
b
ba
bc
bca
c
ca
z
z
z
Do the constraints allow us to generate all subsequences of the string?
We can generate all possible subsequences of the string, and for each subsequence check if it contains any character multiple times. If it doesn’t contain any character multiple times, append it into our result.
Algorithm:
O(2 ^ N * N), where ‘N’ denotes the length of STR.
Since we iterate through 2 ^ N different possibilities and each possibility has a length of at most N, the time complexity is O(2 ^ N * N).
O(2 ^ N * N), where ‘N’ denotes the length of STR.
Since we store at most 2 ^ N different possibilities and each possibility has a length of at most N, the space complexity is O(2 ^ N * N).