VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sub-strings-of-a-string-that-are-prefix-of-the-same-string/

⇱ Sub-strings of a string that are prefix of the same string - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sub-strings of a string that are prefix of the same string

Last Updated : 11 Jul, 2025

Given a string str, the task is to count all possible sub-strings of the given string that are prefix of the same string.

Examples: 

Input: str = "ababc" 
Output:
All possible sub-string are "a", "ab", "aba", "abab", "ababc", "a" and "ab"

Input: str = "abdabc" 
Output:

Approach: Traverse the string character by character, if the current character is equal to the first character of the string then count all possible sub-strings starting from here that are also the prefixes of str and add it to count. After the complete string has been traversed, print the count.

Below is the implementation of the above approach: 


Output
6

Complexity Analysis:

  • Time Complexity: O(N^2) 
  • Auxiliary Space: O(1)

Efficient Approach:

Prerequisite: Z-Algorithm

Approach: Calculate the z-array of the string such that z[i] stores the length of the longest substring starting from i which is also a prefix of string s. Then to count all possible sub-strings of the string that are prefixes of the same string, we just need to add all the values of the z-array since the total number of substrings matching would be equal to the length of the longest substring.

Implementation:


Output
6

Complexity Analysis:

  • Time Complexity: O(n)
  • Auxiliary Space: O(n)
Comment