Given a string, find all combinations of non-overlapping substrings of it.

Please note that the problem specifically targets substrings that are contiguous (i.e., occupy consecutive positions) and inherently maintains the order of elements.

 
For example,

Input:  ABC
 
Output: [A, B, C], [A, BC], [AB, C], [ABC]

 
 
Input:  ABCD
 
Output: [A, B, C, D], [A, B, CD], [A, BC, D], [A, BCD], [AB, C, D], [AB, CD], [ABC, D], [ABCD]

Practice this problem

The idea is to use recursion to solve this problem. For a given string str of length n, consider every prefix str[0, i] of it one by one. We append the prefix to the output string by enclosing it within the parenthesis and recur for the remaining substring str[i+1, n-1]. If every substring of the original string is processed, add the output string to result.

Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Output:

A B C D
A B CD
A BC D
A BCD
AB C D
AB CD
ABC D
ABCD

Java


Download  Run Code

Output:

[[AB, CD], [A, BC, D], [A, BCD], [ABC, D], [A, B, CD], [AB, C, D], [A, B, C, D], [ABCD]]

Python


Download  Run Code

Output:

{(‘AB’, ‘CD’), (‘A’, ‘BCD’), (‘A’, ‘BC’, ‘D’), (‘ABC’, ‘D’), (‘AB’, ‘C’, ‘D’), (‘ABCD’,), (‘A’, ‘B’, ‘C’, ‘D’), (‘A’, ‘B’, ‘CD’)}

The time complexity of the above solution is exponential as there are exactly 2n-1 combinations, where n is the length of the input string.