Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Largest substring of str2 which is a prefix of str1
Next article icon

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

Last Updated : 20 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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




// 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 str
int 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 str
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
int main()
{
    string str = "abcda";
    int n = str.length();
   
    // Function Call
    cout << (countSubStrings(str, n));
}
 
// This code is contributed by harshvijeta0
 
 

Java




// Java implementation of the approach
public 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




# Python3 implementation of the approach
 
# Function to return the
# count of sub-strings starting
# from startIndex that are
# also the prefixes of string
def 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 string
def 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 Code
if __name__ == "__main__" :
     
    string = "ababc"
    n = len(string)
    print(countSubStrings(string, n))
 
# this code is contributed by Ryuga
 
 

C#




// C# implementation of the approach
using 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
 
 

Javascript




<script>
 
// Javascript implementation of the approach
 
// Function to return the
// count of sub-strings starting
// from startIndex that are
// also the prefixes of str
function 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 str
function 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 code
var str = "abcda";
var n = str.length;
 
// Function Call
document.write(countSubStrings(str, n));
 
// This code is contributed by rutvik_56
 
</script>
 
 
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:

C++




#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 s
vector<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;
}
 
 

Python3




# returns an array z such that  z[i]
# stores length of the longest substring starting
# from i which is also a prefix of s
def 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)
 
 

C#




using System;
class GFG {
 
  // returns an array z such that  z[i]
  // stores length of the longest substring starting
  // from i which is also a prefix of string s
  static int[] z_function(string s)
  {
    int n = s.Length;
    int[] z = new int[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] = 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;
  }
 
  public static void Main()
  {
    string s = "abcda";
 
    int n = s.Length;
 
    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 (int i = 0; i < z.Length; i++)
      count += z[i];
 
    Console.WriteLine(count);
  }
}
 
// This code is contributed by Samim Hossain Mondal.
 
 

Javascript




<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 s
function 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 code
let 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 string
let count = 0;
for (let x of z)
    count += x;
 
document.write(count)
 
// This code is contributed by shinjanpatra
 
</script>
 
 

Java




import java.util.*;
 
public class Main {
     
    public static ArrayList<Integer> z_function(String s) {
        int n = s.length();
        ArrayList<Integer> z = new ArrayList<Integer>(Collections.nCopies(n, 0));
        int l = 0, r = 0;
        z.set(0, n);
        for (int i = 1; i < n; ++i) {
            if (i <= r) {
                z.set(i, Math.min(r - i + 1, z.get(i - l)));
            }
            while (i + z.get(i) < n && s.charAt(z.get(i)) == s.charAt(i + z.get(i))) {
                int value = z.get(i) + 1;
z.set(i, value);
 
            }
            if (i + z.get(i) - 1 > r) {
                l = i;
                r = i + z.get(i) - 1;
            }
        }
        return z;
    }
 
    public static void main(String[] args) {
        String s = "abcda";
        int n = s.length();
        ArrayList<Integer> z = z_function(s);
        int count = 0;
        for (int x : z) {
            count += x;
        }
        System.out.println(count);
    }
}
 
 
Output
6

Complexity Analysis:

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


Next Article
Largest substring of str2 which is a prefix of str1

R

rituraj_jain
Improve
Article Tags :
  • Algorithms
  • DSA
  • Strings
  • Technical Scripter
  • Java-Strings
  • prefix
  • substring
  • Technical Scripter 2018
Practice Tags :
  • Algorithms
  • Java-Strings
  • Strings

Similar Reads

  • Find all substrings that are anagrams of another substring of the string S
    Given a string S, the task is to find all the substrings in the string S which is an anagram of another different substring in the string S. The different substrings mean the substring starts at a different index. Examples: Input: S = "aba"Output: a a ab baExplanation:Following substrings are anagra
    6 min read
  • Largest substring of str2 which is a prefix of str1
    Given two string str1 and str2, the task is to find the longest prefix of str1 which is present as a substring of the string str2. Print the prefix if possible else print -1.Examples: Input: str1 = "geeksfor", str2 = "forgeeks" Output: geeks All the prefixes of str1 which are present in str2 are "g"
    5 min read
  • Different substrings in a string that start and end with given strings
    Given a string s and two other strings begin and end, find the number of different substrings in the string which begin and end with the given begin and end strings. Examples: Input : s = "geeksforgeeks" begin = "geeks" end = "for" Output : 1 Input : s = "vishakha" begin = "h" end = "a" Output : 2 T
    9 min read
  • Length of all prefixes that are also the suffixes of given string
    Given a string S consisting of N characters, the task is to find the length of all prefixes of the given string S that are also suffixes of the same string S. Examples: Input: S = "ababababab"Output: 2 4 6 8Explanation: The prefixes of S that are also its suffixes are: "ab" of length = 2"abab" of le
    10 min read
  • Print the longest prefix of the given string which is also the suffix of the same string
    Given string str, the task is to find the longest prefix which is also the suffix of the given string. The prefix and suffix should not overlap. If no such prefix exists then print -1. Examples: Input: str = "aabcdaabc" Output: aabc The string "aabc" is the longest prefix which is also suffix. Input
    8 min read
  • String from prefix and suffix of given two strings
    Given two strings a and b, form a new string of length l, from these strings by combining the prefix of string a and suffix of string b. Examples : Input : string a = remuneration string b = acquiesce length of pre/suffix(l) = 5 Output :remuniesce Input : adulation obstreperous 6 Output :adulatperou
    4 min read
  • Replace two substrings (of a string) with each other
    Given 3 strings S, A and B. The task is to replace every sub-string of S equal to A with B and every sub-string of S equal to B with A. It is possible that two or more sub-strings matching A or B overlap. To avoid confusion about this situation, you should find the leftmost sub-string that matches A
    7 min read
  • Find the Longest Non-Prefix-Suffix Substring in the Given String
    Given a string s of length n. The task is to determine the longest substring t such that t is neither the prefix nor the suffix of string s, and that substring must appear as both prefix and suffix of the string s. If no such string exists, print -1. Example: Input: s = "fixprefixsuffix"Output: fix
    7 min read
  • Remove longest prefix of the String which has duplicate substring
    Given a string S of length N, the task is to remove the longest prefix of the string which has at least one duplicate substring present in S. Note: The duplicate substring cannot be the prefix itself Examples: Input: S = "GeeksforGeeks"Output: "forGeeks"Explanation: The longest substring which has a
    5 min read
  • Find the longest sub-string which is prefix, suffix and also present inside the string | Set 2
    Given string str. The task is to find the longest sub-string which is a prefix, a suffix and a sub-string of the given string, str. If no such string exists then print -1.Examples: Input: str = "geeksisforgeeksinplatformgeeks" Output: geeksInput: str = “fixprefixsuffix” Output: fix Note: The Set-1 o
    9 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences