Count substrings with same first and last characters

2.3

We are given a string S, we need to find count of all contiguous substrings starting and ending with same character.

Examples :

Input  : S = "abcab"
Output : 7
There are 15 substrings of "abcab"
a, ab, abc, abca, abcab, b, bc, bca
bcab, c, ca, cab, a, ab, b
Out of the above substrings, there 
are 7 substrings : a, abca, b, bcab, 
c, a and b.

Input  : S = "aba"
Output : 4
The substrings are a, b, a and aba

Method 1 (Simple): In this approach we use brute force and find all the sub-strings and pass them through our function checkEquality to see if starting and ending characters are same.

C++

// C++ program to count all substrings with same
// first and last characters.
#include <bits/stdc++.h>
using namespace std;

// Returns true if first and last characters
// of s are same.
int checkEquality(string s)
{
    return (s[0] == s[s.size() - 1]);
}

int countSubstringWithEqualEnds(string s)
{
    int result = 0;
    int n = s.length();

    // Starting point of substring
    for (int i = 0; i < n; i++)

       // Length of substring
       for (int len = 1; len <= n-i; len++)

          // Check if current substring has same
          // starting and ending characters.
          if (checkEquality(s.substr(i, len)))
            result++;

    return result;
}

// Driver function
int main()
{
    string s("abcab");
    cout << countSubstringWithEqualEnds(s);
    return 0;
}

Java

// Java program to count all substrings with same
// first and last characters.
public class GFG {
 
    // Returns true if first and last characters
    // of s are same.
    static boolean checkEquality(String s)
    {
        return (s.charAt(0) == s.charAt(s.length() - 1));
    }
     
    static int countSubstringWithEqualEnds(String s)
    {
        int result = 0;
        int n = s.length();
     
        // Starting point of substring
        for (int i = 0; i < n; i++)
     
           // Length of substring
           for (int len = 1; len <= n-i; len++)
     
              // Check if current substring has same
              // starting and ending characters.
              if (checkEquality(s.substring(i, i + len)))
                result++;
     
        return result;
    }
     
    // Driver function
    public static void main(String args[])
    {
        String s = "abcab";
        System.out.println(countSubstringWithEqualEnds(s));
    }
}
// This code is contributed by Sumit Ghosh


Output:

7

Although the above code works fine, it’s not efficient as its time complexity is O(n2). Note that there are n*(n+1)/2 substrings of a string of length n. This solution also requires O(n) extra space as we one by one create all substrings.

 
Method 2 (Space Efficient): In this approach we don’t actually generate substrings rather we traverse the string in such a manner so that we can easily compare first and last characters.

C++

// Space efficient C++ program to count all
// substrings with same first and last characters.
#include <bits/stdc++.h>
using namespace std;

int countSubstringWithEqualEnds(string s)
{
    int result = 0;
    int n = s.length();

    // Iterating through all substrings in
    // way so that we can find first and last
    // character easily
    for (int i=0; i<n; i++)
        for (int j=i; j<n; j++)
            if (s[i] == s[j])
                result++;

    return result;
}

// Driver function
int main()
{
    string s("abcab");
    cout << countSubstringWithEqualEnds(s);
    return 0;
}

Java

// Space efficient Java program to count all
// substrings with same first and last characters.
public class GFG {
  
    static int countSubstringWithEqualEnds(String s)
    {
        int result = 0;
        int n = s.length();
     
        // Iterating through all substrings in
        // way so that we can find first and last
        // character easily
        for (int i = 0; i < n; i++)
            for (int j = i; j < n; j++)
                if (s.charAt(i) == s.charAt(j))
                    result++;
     
        return result;
    }
     
    // Driver function
    public static void main(String args[])
    {
        String s = "abcab";
        System.out.println(countSubstringWithEqualEnds(s));
    }
}
// This code is contributed by Sumit Ghosh


Output:
7

In the above code although we have reduced the extra space to O(1) but time complexity is still O(n^2).

 

Method 3 (Best approach) : Now if we carefully observe then we can realize that the answer just depends on frequencies of characters in the original string. For example in string abcab, frequency of ‘a’ is 2 and substrings contributing to answer are a, abca and a respectively, a total of 3, which is calculated by (frequency of ‘a’+1)C2.

C++

// Most efficient C++ program to count all  
// substrings with same first and last characters.
#include <bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 26;  // assuming lower case only

int countSubstringWithEqualEnds(string s)
{
    int result = 0;
    int n = s.length();

    // Calculating frequency of each character
    // in the string.
    int count[MAX_CHAR] = {0};
    for (int i=0; i<n; i++)
        count[s[i]-'a']++;

    // Computing result using counts
    for (int i=0; i<MAX_CHAR; i++)
        result += (count[i]*(count[i]+1)/2);

    return result;
}

// Driver function
int main()
{
    string s("abcab");
    cout << countSubstringWithEqualEnds(s);
    return 0;
}

Java

// Most efficient Java program to count all  
// substrings with same first and last characters.
public class GFG {
        
      // assuming lower case only
    static final int MAX_CHAR = 26;  
     
    static int countSubstringWithEqualEnds(String s)
    {
        int result = 0;
        int n = s.length();
     
        // Calculating frequency of each character
        // in the string.
        int[] count =  new int[MAX_CHAR];
        for (int i = 0; i < n; i++)
            count[s.charAt(i)-'a']++;
     
        // Computing result using counts
        for (int i = 0; i < MAX_CHAR; i++)
            result += (count[i] * (count[i] + 1) / 2);
     
        return result;
    }
     
    // Driver function
    public static void main(String args[])
    {
        String s = "abcab";
        System.out.println(countSubstringWithEqualEnds(s));
    }
}
// This code is contributed by Sumit Ghosh


Output:
7

The above code has time complexity of O(n) and requires O(1) extra space.

Recursive solution to count substrings with same first and last characters

This article is contributed by Aditya Gupta. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above..

GATE CS Corner    Company Wise Coding Practice

Recommended Posts:



2.3 Average Difficulty : 2.3/5.0
Based on 48 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.