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 given string is ‘n’ our updated string can have maximum length of n + (n-1) i.e. 2n-1. So we create 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 number of Gaps are 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
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Print all possible strings that can be made by placing spaces
- Count number of strings (made of R, G and B) using given combination
- Find the longest string that can be made up of other strings from the array
- Check if two strings can be made equal by swapping one character among each other
- Check whether two strings can be made equal by increasing prefixes
- Check whether two strings can be made equal by copying their characters with the adjacent ones
- Print all interleavings of given two strings
- Print the most occurring character in an array of strings
- Print all possible strings of length k that can be formed from a set of n characters
- Print all pairs of anagrams in a given array of strings
- Print Strings In Reverse Dictionary Order Using Trie
- Print all possible joints of a Trie constructed from a given list of strings
- Print common characters of two Strings in alphabetical order
- Print the final string when minimum value strings get concatenated in every operation
- Print array of strings in sorted order without copying one string into another
- Print all distinct circular strings of length M in lexicographical order
- Python code to print common characters of two Strings in alphabetical order
- Remove spaces from a given string
- C++ Program to remove spaces from a string
- Remove extra spaces from a string