Last Updated: 16 Mar, 2021

All substrings

Easy
Asked in company
Oracle

Problem statement

For a given input string(str), write a function to print all the possible substrings.

Substring
A substring is a contiguous sequence of characters within a string. 
Example: "cod" is a substring of "coding". Whereas "cdng" is not as the characters taken are not contiguous
Input Format:
The first and only line of input contains a string without any leading and trailing spaces. All the characters in the string would be in lower case.
Output Format:
Print all the substrings possible, where every substring is printed on a separate line.
Note:
The order in which the substrings are printed does not matter.
Constraints:
0 <= N <= 10^3
Where N is the length of the input string.

Time Limit: 1 second

Approaches

01 Approach

  • We maintain 3 variables i, j, k.
  • i is for the starting index of the substring.
  • j is for the ending index of the substring.
  • Finally, we iterate k from i to j and print each character of the substring.

02 Approach

  • We maintain 3 variables i, j and a string temp.
  • i is for the starting index of the substring.
  • j is for the ending index of the substring.
  • Here we make use of the fact the when we increment j to j + 1 only one character is added to the last substring we printed.
  • So we maintain a string temp which is our current substring.
  • Every time we increment j we append the j +1th character to the temp string.
  • Finally, we output the string temp in each iteration.