Solution: Java program to find all substrings of a String.
For example: If the input is “abb” then the output should be “a”, “b”,”b”, “ab”, “bb”, “abb”
We will use the String class’s subString method to find all substrings.
Program:
public class SubstringsOfStringMain
{
public static void main(String args[]) {
String str="abbc";
System.out.println("All substring of abbc are:");
for (int i = 0; i < str.length(); i++) {
for (int j = i+1; j <= str.length(); j++) {
System.out.println(str.substring(i,j));
}
}
Set<String> substrings = new HashSet<>();
generateSubstrings(str, 0, "", substrings);
// Print unique substrings
for (String substring : substrings) {
System.out.println(substring);
}
}
static void generateSubstrings(String str, int index, String current, Set<String> substrings) { if (index == str.length()) {
substrings.add(current); // Add the current substring
return;
}
// Include the current character
generateSubstrings(str, index + 1, current + str.charAt(index), substrings);
// Exclude the current character
generateSubstrings(str, index + 1, current, substrings);
}
}When you run the above program, you will get the following output:
All substring of abbc are: a ab abb abbc b bb bbc b bc c The above solution is of o(n^3) time complexity. As we have two loops and also String’s substring method has a time complexity of o(n). If you want to find all distinct substrings of String, then use HashSet to remove duplicates.
Python code
def find_all_substrings(s: str): result = [] n = len(s) for i in range(n): for j in range(i + 1, n + 1): result.append(s[i:j]) return result if __name__ == "__main__": for sub in find_all_substrings("abc"): print(sub)
📌 Final Comparison
| Approach | Time Complexity | Space Complexity | Best Use |
|---|---|---|---|
| Nested loops with substring | O(n²) | O(n²) | ⭐ Best general approach |
| Using recursion (build substrings) | O(n²) | O(n²) | ✔ Works, but more complex |
| Suffix tree (advanced) | O(n²) lower bound* | O(n) | ⚠ Complex, not needed here |