VOOZH about

URL: https://www.geeksforgeeks.org/dsa/program-print-substrings-given-string/

⇱ All substrings of a given String - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

All substrings of a given String

Last Updated : 13 Feb, 2026

Given a string s, containing lowercase alphabetical characters. The task is to print all non-empty substrings of the given string.

Examples : 

Input : s = "abc"
Output : "a", "ab", "abc", "b", "bc", "c"

Input : s = "ab"
Output : "a", "ab", "b"

Input : s = "a"
Output : "a"

[Approach 1] Using Iteration - O(n^3) Time and O(n^3) Space

The idea is to use two nested loops. The outer loop selects the starting index from 0 to n-1, and for each starting index, the inner loop selects the ending index from that position up to n-1.


Output
a ab abc b bc c 

[Approach 2] Using Recursion - O(n^3) Time and O(n^3) Space

The idea is to use recursion to generate all substrings. Start from index 0 and build a current string cur by adding one character at a time. After adding each character, store cur in the result list. Then recursively move to the next index to continue building longer substrings. If cur becomes empty, skip the current character and start forming substrings from the next index.


Output
a ab abc b bc c 
Comment
Article Tags: