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

22 Apr, 2022
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: 7 All possible sub-string are “a”, “ab”, “aba”, “abab”, “ababc”, “a” and “ab”
Input: str = “abdabc” Output: 8 
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: 
C++14
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <iostream>#include <string>using namespace std; // Function to return the// count of sub-strings starting// from startIndex that are// also the prefixes of strint subStringsStartingHere(string str, int n,                            int startIndex){    int count = 0, i = 1;    while (i <= n)    {        if (str.substr(0,i) ==                str.substr(startIndex, i))        {            count++;        }        else            break;        i++;    }     return count;}  // Function to return the// count of all possible sub-strings// of str that are also the prefixes of strint countSubStrings(string str, int n){    int count = 0;    for (int i = 0; i < n; i++)    {         // If current character is equal to        // the starting character of str        if (str[i] == str[0])            count += subStringsStartingHere(str,                                           n, i);    }    return count;} // Driver codeint main(){    string str = "abcda";    int n = str.length();       // Function Call    cout << (countSubStrings(str, n));} // This code is contributed by harshvijeta0
// Java implementation of the approachpublic class GFG{   // Function to return  // the count of sub-strings starting  // from startIndex that  // are also the prefixes of str  public static int subStringsStartingHere(                                String str, int n,                                    int startIndex)  {    int count = 0, i = startIndex + 1;    while (i <= n)    {      if (str.startsWith(str.substring(                                 startIndex, i)))      {        count++;      }      else        break;      i++;    }    return count;  }   // Function to return the  // count of all possible sub-strings  // of str that are also the prefixes of str  public static int countSubStrings(String str,                                         int n)  {    int count = 0;     for (int i = 0; i < n; i++)    {       // If current character is equal to      // the starting character of str      if (str.charAt(i) == str.charAt(0))        count += subStringsStartingHere(str, n, i);    }     return count;  }   // Driver code  public static void main(String[] args)  {    String str = "ababc";    int n = str.length();    System.out.println(countSubStrings(str, n));  }}
# Python3 implementation of the approach # Function to return the# count of sub-strings starting# from startIndex that are# also the prefixes of stringdef subStringsStartingHere(string, n,                           startIndex):    count = 0    i = startIndex + 1         while(i <= n) :        if string.startswith(                 string[startIndex : i]):            count += 1        else :            break                 i += 1         return count # Function to return the# count of all possible sub-strings# of string that are also# the prefixes of stringdef countSubStrings(string, n) :    count = 0         for i in range(n) :                 # If current character is equal to         # the starting character of str        if string[i] == string[0] :            count += subStringsStartingHere(                              string, n, i)         return count  # Driver Codeif __name__ == "__main__" :         string = "ababc"    n = len(string)    print(countSubStrings(string, n)) # this code is contributed by Ryuga
// C# implementation of the approachusing System;class GFG{      // Function to return the    // count of sub-strings starting    // from startIndex that    // are also the prefixes of str    static int subStringsStartingHere(                               String str, int n,                                   int startIndex)    {        int count = 0, i = startIndex + 1;        while (i <= n) {            if (str.StartsWith(str.Substring(                  startIndex, i-startIndex)))            {                count++;            }            else                break;            i++;        }          return count;    }      // Function to return the    // count of all possible sub-strings    // of str that are also the prefixes of str    static int countSubStrings(String str, int n)    {        int count = 0;          for (int i = 0; i < n; i++) {              // If current character is equal to            // the starting character of str            if (str[i] == str[0])                count += subStringsStartingHere(                                        str, n, i);        }          return count;    }      // Driver code    static public void Main(String []args)    {        String str = "ababc";        int n = str.Length;        Console.WriteLine(countSubStrings(str, n));    }}//contributed by Arnab Kundu
<script> // Javascript implementation of the approach // Function to return the// count of sub-strings starting// from startIndex that are// also the prefixes of strfunction subStringsStartingHere(str, n,                                startIndex){    var count = 0, i = startIndex + 1;         while (i <= n)    {        if (str.startsWith(            str.substring(startIndex, i)))        {            count++;        }        else            break;                     i++;    }    return count;} // Function to return the count of all// possible sub-strings of str that are// also the prefixes of strfunction countSubStrings(str, n){    var count = 0;    for(var i = 0; i < n; i++)    {                 // If current character is equal to        // the starting character of str        if (str[i] == str[0])            count += subStringsStartingHere(str,                                            n, i);    }    return count;} // Driver codevar str = "abcda";var n = str.length; // Function Calldocument.write(countSubStrings(str, n)); // This code is contributed by rutvik_56 </script>
6
Time Complexity: O(N^2) Auxiliary Space: O(1)
Efficient Approach:
Prerequisite: Z-Algorithm
Approach: Calculate z-array of the string such that  z[i] stores 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 prefix 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 longest substring.
Implementation of the above approach:-
C++
Python3
Javascript
#include <bits/stdc++.h>using namespace std; // returns an array z such that  z[i]// stores length of the longest substring starting// from i which is also a prefix of string svector<int> z_function(string s){    int n = (int)s.length();    vector<int> z(n);    // consider a window [l,r]    // which matches with prefix of s    int l = 0, r = 0;    z[0] = n;    for (int i = 1; i < n; ++i) {        // when i<=r, we make use of already computed z        // value for some smaller index        if (i <= r)            z[i] = min(r - i + 1, z[i - l]);         // if i>r nothing matches so we will calculate        // z[i] using naive way.        while (i + z[i] < n && s[z[i]] == s[i + z[i]])            ++z[i];        // update window size        if (i + z[i] - 1 > r)            l = i, r = i + z[i] - 1;    }    return z;} int main(){    string s = "abcda";     int n = s.length();     vector<int> z = z_function(s);     // stores the count of    // Sub-strings of a string that    // are prefix of the same string    int count = 0;     for (auto x : z)        count += x;     cout << count << '\n';     return 0;}
# returns an array z such that  z[i]# stores length of the longest substring starting# from i which is also a prefix of sdef z_function(s):    n = len(s)    z=[0]*n    # consider a window [l,r]    # which matches with prefix of s    l = 0; r = 0    z[0] = n    for i in range(1, n) :        # when i<=r, we make use of already computed z        # value for some smaller index        if (i <= r):            z[i] = min(r - i + 1, z[i - l])         # if i>r nothing matches so we will calculate        # z[i] using naive way.        while (i + z[i] < n and s[z[i]] == s[i + z[i]]):            z[i]+=1        # update window size        if (i + z[i] - 1 > r):            l = i; r = i + z[i] - 1         return z  if __name__ == '__main__':    s = "abcda"     n = len(s)     z = z_function(s)     # stores the count of    # Sub-strings of a that    # are prefix of the same string    count = 0     for x in z:        count += x     print(count)
<script> // JavaScript code for the approach // returns an array z such that  z[i]// stores length of the longest substring starting// from i which is also a prefix of string sfunction z_function(s){    let n = s.length;    let z = new Array(n).fill(0);         // consider a window [l,r]    // which matches with prefix of s    let l = 0, r = 0;    z[0] = n;    for (let i = 1; i < n; i++)    {             // when i<=r, we make use of already computed z        // value for some smaller index        if (i <= r)            z[i] = Math.min(r - i + 1, z[i - l]);         // if i>r nothing matches so we will calculate        // z[i] using naive way.        while (i + z[i] < n && s[z[i]] == s[i + z[i]])            z[i]++;        // update window size        if (i + z[i] - 1 > r)            l = i, r = i + z[i] - 1;    }    return z;} // driver codelet s = "abcda";let n = s.length;let z = z_function(s); // stores the count of// Sub-strings of a string that// are prefix of the same stringlet count = 0;for (let x of z)    count += x; document.write(count) // This code is contributed by shinjanpatra </script>
6
Time Complexity: O(n)
Auxiliary Space: O(n) 
ankthon
andrew1234
Rajput-Ji
harshvijeta0
rutvik_56
pankajsharmagfg
ashutoshsinghgeeksforgeeks
amartyaghoshgfg
varshagumber28
surinderdawra388
shinjanpatra
Java-Strings
prefix
substring
Technical Scripter 2018
Algorithms
Strings
Technical Scripter
Java-Strings
Strings
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.