Print all substrings of a given string
EasyUpdated: May 29, 2025
Problem
Given a string, write a program to return all possible substrings of that string. A substring is a contiguous sequence of characters within a string.
Examples
Example 1
Input: "abc"
Output: ["a", "ab", "abc", "b", "bc", "c"]
Explanation: The substrings of "abc" are generated by iterating through each starting position of the string and extending the substring until the end of the string.
Example 2
Input: "ab"
Output: ["a", "ab", "b"]
Explanation: From "ab", you take each starting position, extending from each starting point to generate "a", "ab", and "b".
Solution
Method 1 - Naive
- To generate all substrings:
- Start at every possible position in the string (known as the start index).
- Extend the substring from the start position to every length that is valid, ending only when the end index reaches the end of the input string.
- Use two nested loops: one for selecting the start position and one for calculating all substrings starting from the current position.
Approach
- Use nested loops:
- The outer loop selects each character in the string as the starting point (start index).
- The inner loop iterates through the possible lengths starting from the current character, generating substrings dynamically.
- Collect each substring into a list or directly print them.
In the Solution Class, these methods are encapsulated to compute substrings efficiently and maintain readability.
Code
Java
public class Solution {
public List<String> generateSubstrings(String inputString) {
List<String> substrings = new ArrayList<>();
int n = inputString.length();
for (int start = 0; start < n; start++) { // Outer loop for starting position
for (int end = start; end < n; end++) { // Inner loop to form substrings
substrings.add(inputString.substring(start, end + 1)); // Extract and add substring
}
}
return substrings;
}
// Example usage:
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.generateSubstrings("abc"));
}
}
Python
class Solution:
def generate_substrings(self, input_string: str):
substrings = []
n = len(input_string)
for start in range(n): # Outer loop for starting position
for end in range(start, n): # Inner loop to form substrings
substrings.append(input_string[start:end + 1]) # Append the substring
return substrings
# Example usage:
solution = Solution()
print(solution.generate_substrings("abc"))
Complexity
- ⏰ Time complexity:
O(n^2). The outer loop runsntimes (once for each character), and the inner loop runs up tontimes for each outer loop iteration. This results in quadratic complexity. - 🧺 Space complexity:
O(n^2). If storing all substrings into a list, the list can grow to a size proportional to the number of substrings.