Given a string you need to print all possible strings that can be made by placing spaces (zero or one) in between them.
Input: str = "ABC" Output: ABC AB C A BC A B C
The idea is to use recursion and create a buffer that one by one contains all output strings having spaces. We keep updating buffer in every recursive call. If the length of the given string is ‘n’ our updated string can have a maximum length of n + (n-1) i.e. 2n-1. So we create a buffer size of 2n (one extra character for string termination).
We leave 1st character as it is, starting from the 2nd character, we can either fill a space or a character. Thus one can write a recursive function like below.
ABCD ABC D AB CD AB C D A BCD A BC D A B CD A B C D
Time Complexity: Since the number of Gaps is n-1, there are total 2^(n-1) patters each having length ranging from n to 2n-1. Thus overall complexity would be O(n*(2^n)).
This article is contributed by Gaurav Sharma. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Print all possible strings that can be made by placing spaces
- Check whether two strings can be made equal by reversing substring of equal length from both strings
- Check if all strings of an array can be made same by interchanging characters
- Print all possible strings of length k that can be formed from a set of n characters
- Check whether two strings can be made equal by increasing prefixes
- Find the longest string that can be made up of other strings from the array
- Check whether two strings can be made equal by copying their characters with the adjacent ones
- Check if two strings can be made equal by swapping one character among each other
- Print all Strings from array A having all strings from array B as subsequence
- Check if all bits can be made same by flipping two consecutive bits
- All possible strings of any length that can be formed from a given string
- How to remove all white spaces from a String in Java?
- Print all possible joints of a Trie constructed from a given list of strings
- Print all possible palindromic string formed using any pair of given strings
- Print all strings of maximum length from an array of strings
- Count number of strings (made of R, G and B) using given combination
- Check if a two character string can be made using given words
- Check if string can be made lexicographically smaller by reversing any substring
- Check whether the string S1 can be made equal to S2 with the given operation
- Count of distinct Strings possible by swapping prefixes of pairs of Strings from the Array