Count substrings with different first and last characters - GeeksforGeeks

21 May, 2021
Given a string S, the task is to print the count of substrings from a given string whose first and last characters are different.
Examples:
Input: S = “abcab”Output: 8Explanation: There are 8 substrings having first and last characters different {ab, abc, abcab, bc, bca, ca, cab, ab}.
Input: S = “aba”Output: 2Explanation: There are 2 substrings having first and last characters different {ab, ba}.
Naive Approach: The idea is to generate all possible substrings of a given string and for each substring, check if the first and the last characters are different or not. If found to be true, then increment the count by 1 and check for the next substring. Print the count after traversal of all the substring.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to count the substrings// having different first and last// charactersint countSubstring(string s, int n){    // Store the final count    int ans = 0;     // Loop to traverse the string    for (int i = 0; i < n; i++) {         // Counter for each iteration        int cnt = 0;         // Iterate over substrings        for (int j = i + 1; j < n; j++) {             // Compare the characters            if (s[j] != s[i])                 // Increase count                cnt++;        }         // Adding count of substrings        // to the final count        ans += cnt;    }     // Print the final count    cout << ans;} // Driver Codeint main(){    // Given string    string S = "abcab";     // Length of the string    int N = 5;     // Function Call    countSubstring(S, N);     return 0;}
// Java program for the above approachimport java.util.*;import java.lang.*;import java.io.*; class GFG{     // Function to count the substrings// having different first and last// charactersstatic void countSubstring(String s, int n){         // Store the final count    int ans = 0;     // Loop to traverse the string    for(int i = 0; i < n; i++)    {                 // Counter for each iteration        int cnt = 0;         // Iterate over substrings        for(int j = i + 1; j < n; j++)        {                         // Compare the characters            if (s.charAt(j) != s.charAt(i))                 // Increase count                cnt++;        }         // Adding count of substrings        // to the final count        ans += cnt;    }     // Print the final count    System.out.print(ans);}     // Driver Codepublic static void main(String[] args){         // Given string    String S = "abcab";     // Length of the string    int N = 5;     // Function call    countSubstring(S, N);}} // This code is contributed by code_hunt
# Python3 program for the above approach # Function to count the substrings# having different first and last# charactersdef countSubstring(s, n):     # Store the final count    ans = 0     # Loop to traverse the string    for i in range(n):         # Counter for each iteration        cnt = 0         # Iterate over substrings        for j in range(i + 1, n):             # Compare the characters            if (s[j] != s[i]):                 # Increase count                cnt += 1                 # Adding count of substrings        # to the final count        ans += cnt         # Print the final count    print(ans) # Driver Code # Given stringS = "abcab" # Length of the stringN = 5 # Function callcountSubstring(S, N) # This code is contributed by code_hunt
// C# program for the above approachusing System;using System.Collections;using System.Collections.Generic;using System.Text; class GFG{     // Function to count the substrings// having different first and last// charactersstatic void countSubstring(string s, int n){         // Store the final count    int ans = 0;     // Loop to traverse the string    for(int i = 0; i < n; i++)    {                 // Counter for each iteration        int cnt = 0;         // Iterate over substrings        for(int j = i + 1; j < n; j++)        {                         // Compare the characters            if (s[j] != s[i])                 // Increase count                cnt++;        }         // Adding count of substrings        // to the final count        ans += cnt;    }     // Print the final count    Console.Write(ans);}     // Driver Codepublic static void Main(string[] args){         // Given string    string S = "abcab";     // Length of the string    int N = 5;     // Function call    countSubstring(S, N);}} // This code is contributed by rutvik_56
<script> // JavaScript program for// the above approach // Function to count the substrings// having different first and last// charactersfunction countSubstring(s, n){          // Store the final count    let ans = 0;      // Loop to traverse the string    for(let i = 0; i < n; i++)    {                  // Counter for each iteration        let cnt = 0;          // Iterate over substrings        for(let j = i + 1; j < n; j++)        {                          // Compare the characters            if (s[j] != s[i])                  // Increase count                cnt++;        }          // Adding count of substrings        // to the final count        ans += cnt;    }      // Print the final count    document.write(ans);}  // Driver code     // Given string    let S = "abcab";      // Length of the string    let N = 5;      // Function call    countSubstring(S, N);           // This code is contributed by splevel62.</script>
8
Time Complexity: O(N2)Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized using Map by to store the frequency of the characters of the string. Follow the steps below to solve the problem:
Initialize two variables, one for counting different characters for every iteration (say cur) and one to store the final count of substrings (say ans).Initialize a map M to store the frequency of all characters in it.Traverse the given string and for each character, follow the steps below:Iterate the map M.If the first element i.e., the key of the map is not the same as the current character, then proceed.Otherwise, add the value corresponding to the current character.After traversal of the Map, add cur to the final result i.e., ans += cur.
Initialize two variables, one for counting different characters for every iteration (say cur) and one to store the final count of substrings (say ans).
Initialize a map M to store the frequency of all characters in it.
Traverse the given string and for each character, follow the steps below:Iterate the map M.If the first element i.e., the key of the map is not the same as the current character, then proceed.Otherwise, add the value corresponding to the current character.
Iterate the map M.
If the first element i.e., the key of the map is not the same as the current character, then proceed.
Otherwise, add the value corresponding to the current character.
After traversal of the Map, add cur to the final result i.e., ans += cur.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to count the substrings// having different first & last characterint countSubstring(string s, int n){    // Stores frequency of each char    map<char, int> m;     // Loop to store frequency of    // the characters in a Map    for (int i = 0; i < n; i++)        m[s[i]]++;     // To store final result    int ans = 0;     // Traversal of string    for (int i = 0; i < n; i++) {         // Store answer for every        // iteration        int cnt = 0;        m[s[i]]--;         // Map traversal        for (auto value : m) {             // Compare current char            if (value.first == s[i]) {                continue;            }            else {                cnt += value.second;            }        }         ans += cnt;    }     // Print the final count    cout << ans;} // Driver Codeint main(){    // Given string    string S = "abcab";     // Length of the string    int N = 5;     // Function Call    countSubstring(S, N);     return 0;}
// Java program for the above approachimport java.util.*; class GFG{ // Function to count the subStrings// having different first & last characterstatic void countSubString(char []s, int n){         // Stores frequency of each char    HashMap<Character,            Integer> mp = new HashMap<Character,                                      Integer>();     // Loop to store frequency of    // the characters in a Map    for(int i = 0; i < n; i++)         if (mp.containsKey(s[i]))        {            mp.put(s[i], mp.get(s[i]) + 1);        }        else        {            mp.put(s[i], 1);        }     // To store final result    int ans = 0;     // Traversal of String    for(int i = 0; i < n; i++)    {                 // Store answer for every        // iteration        int cnt = 0;        if (mp.containsKey(s[i]))        {            mp.put(s[i], mp.get(s[i]) - 1);             // Map traversal            for(Map.Entry<Character,                          Integer> value : mp.entrySet())            {                                 // Compare current char                if (value.getKey() == s[i])                {                    continue;                }                else                {                    cnt += value.getValue();                }            }            ans += cnt;        }    }         // Print the final count    System.out.print(ans);} // Driver Codepublic static void main(String[] args){         // Given String    String S = "abcab";     // Length of the String    int N = 5;     // Function call    countSubString(S.toCharArray(), N);}} // This code is contributed by Amit Katiyar
# Python3 program for the above approach # Function to count the substrings# having different first & last characterdef countSubstring(s, n):      # Stores frequency of each char    m = {}     # Loop to store frequency of    # the characters in a Map    for i in range(n):        if s[i] in m:            m[s[i]] += 1        else:            m[s[i]] = 1     # To store final result    ans = 0     # Traversal of string    for i in range(n):         # Store answer for every        # iteration        cnt = 0                 if s[i] in m:            m[s[i]] -= 1        else:            m[s[i]] = -1         # Map traversal        for value in m:             # Compare current char            if (value == s[i]):                continue            else:                cnt += m[value]         ans += cnt     # Print the final count    print(ans) # Driver code # Given stringS = "abcab" # Length of the stringN = 5 # Function CallcountSubstring(S, N) # This code is contributed by divyeshrabadiya07
// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to count the subStrings// having different first & last characterstatic void countSubString(char []s, int n){         // Stores frequency of each char    Dictionary<char,               int> mp = new Dictionary<char,                                        int>();     // Loop to store frequency of    // the characters in a Map    for(int i = 0; i < n; i++)         if (mp.ContainsKey(s[i]))        {            mp[s[i]] = mp[s[i]] + 1;        }        else        {            mp.Add(s[i], 1);        }     // To store readonly result    int ans = 0;     // Traversal of String    for(int i = 0; i < n; i++)    {                 // Store answer for every        // iteration        int cnt = 0;        if (mp.ContainsKey(s[i]))        {            mp[s[i]] = mp[s[i]] - 1;             // Map traversal            foreach(KeyValuePair<char,                                 int> value in mp)            {                                 // Compare current char                if (value.Key == s[i])                {                    continue;                }                else                {                    cnt += value.Value;                }            }            ans += cnt;        }    }         // Print the readonly count    Console.Write(ans);} // Driver Codepublic static void Main(String[] args){         // Given String    String S = "abcab";     // Length of the String    int N = 5;     // Function call    countSubString(S.ToCharArray(), N);}} // This code is contributed by Amit Katiyar
<script>// Javascript program for the above approach // Function to count the substrings// having different first & last characterfunction countSubstring(s, n){     // Stores frequency of each char    var m = new Map();     // Loop to store frequency of    // the characters in a Map    for (var i = 0; i < n; i++)    {        if(m.has(s[i]))            m.set(s[i], m.get(s[i])+1)        else             m.set(s[i], 1)    }     // To store final result    var ans = 0;     // Traversal of string    for (var i = 0; i < n; i++) {         // Store answer for every        // iteration        var cnt = 0;        if(m.has(s[i]))            m.set(s[i], m.get(s[i])-1)              // Map traversal        m.forEach((value, key) => {                         // Compare current char            if (key != s[i]) {                cnt += value;            }         });         ans += cnt;    }     // Print the final count    document.write( ans);} // Driver Code // Given stringvar S = "abcab"; // Length of the stringvar N = 5; // Function CallcountSubstring(S, N); // This code is contributed by itsok.</script>
8
Time Complexity: O(N*26)Auxiliary Space: O(N)
 
rutvik_56
code_hunt
amit143katiyar
divyeshrabadiya07
splevel62
itsok
cpp-map
frequency-counting
Greedy
Hash
Strings
Hash
Strings
Greedy
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Split the given array into K sub-arrays such that maximum sum of all sub arrays is minimum
Program for First Fit algorithm in Memory Management
Optimal Page Replacement Algorithm
Program for Best Fit algorithm in Memory Management
Bin Packing Problem (Minimize number of used Bins)
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Count pairs with given sum
Hashing | Set 3 (Open Addressing)