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.
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".
publicclassSolution {
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 positionfor (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:publicstaticvoidmain(String[] args) {
Solution solution =new Solution();
System.out.println(solution.generateSubstrings("abc"));
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution:
defgenerate_substrings(self, input_string: str):
substrings = []
n = len(input_string)
for start in range(n): # Outer loop for starting positionfor end in range(start, n): # Inner loop to form substrings substrings.append(input_string[start:end +1]) # Append the substringreturn substrings
# Example usage:solution = Solution()
print(solution.generate_substrings("abc"))
⏰ Time complexity: O(n^2). The outer loop runs n times (once for each character), and the inner loop runs up to n times 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.