![]() |
VOOZH | about |
Given a string, we have to find out all its subsequences of it. A String is said to be a subsequence of another String, if it can be obtained by deleting 0 or more character without changing its order.
For example, sub-sequences of "geeks" are
Examples:
Input : ab
Output : "", "a", "b", "ab"Input : abc
Output : "", "a", "b", "c", "ab", "ac", "bc", "abc"
Table of Content
We begin with the last character and for every character, we make two choices, we either pick it or do not pick it and make two recursive calls. This way generate all possible subsequences.
ab a b
Time Complexity: O(n2^n) This is because, for a string of length n, we generate a total of 2^n sub-sequences.
Auxiliary Space : O(n) The recursive function call stack requires O(n) space for the worst case, where n is the length of the given string.
Further Optimization : Instead of generating a substring every-time, we can pass index as additional parameter and pass reference of the same string.
One by one fix characters and recursively generate all subsets starting from them. After every recursive call, we remove the last character so that the next permutation can be generated.
a ab b
Time Complexity: O(n * 2n), where n is the size of the given string
Auxiliary Space: O(n), due to recursive call stack
String = "abc"
All combinations of abc can be represented by all binary representation from 0 to (2^n - 1) where n is the size of the string . The following representation clears things up.
Note : We can also take zero into consideration which will eventually give us an empty set "", the only change in code will be starting loop from zero.
001 -> "c"
010 -> "b"
011 -> "bc
100 -> "a"
101 -> "ac"
110 -> "ab"
111 -> "abc"As you can observe we get unique sub-sequences for every set-bit and thus no 2 combinations can be same as 2 numbers cannot have same binary representation.
Below is the implementation of the above approach:
a b ab
Time Complexity: O(n* 2^n)
Auxiliary Space: O(n)