Python program to print the substrings that are prefix of the given string

Given a string, print all the possible substrings which are also the prefix of the given string.

Examples:

Input : ababc         
Output : a, ab, aba, abab, ababc, a, ab
          
Input : abdabc          
Output : a, ab, abd, abda, abdab, abdabc, a, ab          

Approach:
We use two variables: start and end to keep track of the current substring and follow the below conditions until start < len(string):



  • If the current substring is also the prefix of the given string, print it and increment end. If end == len(string), increment start and end = start
  • Else increment start and end = start

Logic to check if the current substring is a prefix of the given string:

string[end] == string[end-start]

This makes use of the fact that if a substring of length L is a prefix of the given string, then the substring of length L+1 obtained after including the next character ch in the sequence is also a prefix of the given string if the character at (L+1) index in the string is equal to ch.

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

      
# Python3 code to find all possible substrings that 
# are also the prefix of the given string
   
# Function to print all the special substrings
def func(string):
       
    # Used to store the starting and
    # ending index of the substrings
    start, end = 0, 0
       
    while start < len(string):
           
        # If substring is also the prefix
        if string[end] == string[end-start]:
               
            # Print the substring
            print(string[start:end + 1], end= " ")
            end += 1
               
            if end == len(string):
                start += 1
                end = start
           
        # Increment the starting 
        # index of the substring        
        else:
            start += 1
            end = start
               
if __name__ == "__main__":
       
    string = "ababc"
    func(string)

chevron_right


Output:

a ab aba abab ababc a ab

Time Complexity: O(n^2)



My Personal Notes arrow_drop_up

I like solving puzzles

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.