Skip to content
Related Articles

Related Articles

Improve Article
Number of substrings with each character occurring even times
  • Difficulty Level : Medium
  • Last Updated : 03 Jun, 2021

Given a string S consisting of N lowercase alphabets, the task is to count the number of substrings whose frequency of each character is even.

Examples:

Input: S = “abbaa”
Output: 4
Explanation:
The substrings having frequency of each character is even are {“abba”, “aa”, “bb”, “bbaa”}.
Therefore, the count is 4.

Input: S = “geeksforgeeks”
Output: 2

Naive Approach: The simplest approach to solve the given problem is to generate all possible substrings of the given string and count those substrings having even frequency of every character. After checking for all substrings, print the total count obtained.



Below is the implementation of the above approach:

Java




// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
public class GFG
{
 
    // Function to count substrings having
    // even frequency of each character
    static int subString(String s, int n)
    {
 
        // Stores the total
        // count of substrings
        int count = 0;
 
        // Traverse the range [0, N]:
        for (int i = 0; i < n; i++) {
 
            // Traverse the range [i + 1, N]
            for (int len = i + 1; len <= n; len++) {
 
                // Stores the substring over
                // the range of indices [i, len]
                String test_str = s.substring(i, len);
 
                // Stores the frequency of characters
                HashMap<Character, Integer> res
                    = new HashMap<>();
 
                // Count frequency of each character
                for (char keys : test_str.toCharArray()) {
                    res.put(keys,
                            res.getOrDefault(keys, 0) + 1);
                }
 
                int flag = 0;
 
                // Traverse the dictionary
                for (char keys : res.keySet()) {
 
                    // If any of the keys
                    // have odd count
                    if (res.get(keys) % 2 != 0) {
 
                        flag = 1;
                        break;
                    }
                }
               
                // Otherwise
                if (flag == 0)
                    count += 1;
            }
        }
 
        // Return count
        return count;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        String S = "abbaa";
        int N = S.length();
        System.out.println(subString(S, N));
    }
}
 
// This code is contributed by Kingash.

Python3




# Python program for the above approach
 
# Function to count substrings having
# even frequency of each character
def subString(s, n):
 
    # Stores the total
    # count of substrings
    count = 0
 
    # Traverse the range [0, N]:
    for i in range(n):
       
        # Traverse the range [i + 1, N]
        for len in range(i + 1, n + 1):
           
            # Stores the substring over
            # the range of indices [i, len]
            test_str = (s[i: len])
 
            # Stores the frequency of characters
            res = {}
 
            # Count frequency of each character
            for keys in test_str:
                res[keys] = res.get(keys, 0) + 1
                 
            flag = 0
             
            # Traverse the dictionary
            for keys in res:
               
                # If any of the keys
                # have odd count
                if res[keys] % 2 != 0:
 
                    flag = 1
                    break
                     
            # Otherwise
            if flag == 0:
                count += 1
 
    # Return count
    return count
 
 
# Driver Code
 
S = "abbaa"
N = len(S)
print(subString(S, N))

Javascript




<script>
 
// JavaScript program for the above approach
// Function to count substrings having
// even frequency of each character
function subString(s, n)
{
     
    // Stores the total
    // count of substrings
    var count = 0;
     
    // Traverse the range [0, N]:
    for(var i = 0; i < n; i++)
    {
         
        // Traverse the range [i + 1, N]
        for(var len = i + 1; len <= n; len++)
        {
             
            // Stores the substring over
            // the range of indices [i, len]
            var test_str = s.substring(i, len);
             
            // Stores the frequency of characters
            var res = {};
             
            // Count frequency of each character
             
            var temp = test_str.split("");
             
            for(const keys of temp)
            {
                res[keys] = (res[keys] ? res[keys] : 0) + 1;
            }
             
            var flag = 0;
             
            // Traverse the dictionary
            for(const [key, value] of Object.entries(res))
            {
                 
                // If any of the keys
                // have odd count
                if (res[key] % 2 != 0)
                {
                    flag = 1;
                    break;
                }
            }
             
            // Otherwise
            if (flag == 0) count += 1;
        }
    }
     
    // Return count
    return count;
}
 
// Driver Code
var S = "abbaa";
var N = S.length;
 
document.write(subString(S, N));
 
// This code is contributed by rdtank
 
</script>
Output: 
4

 

Time Complexity: O(N2 * 26)
Auxiliary Space: O(N)

Efficient Approach: The above approach can be optimized by using the concept of Bitmasking and dictionary. Follow the below steps to solve the problem:

  • Initialize a dictionary, say hash to store the count of a character.
  • Initialize two variables, say count as 0 and pre as 0 to store the total count of substrings having an even count of each character and to store the mask of characters included in the substring.
  • Traverse the given string and perform the following steps:
    • Flip the (S[i] – ‘a’)th bit in the variable pre.
    • Increment the count by hash[pre] and the count of pre in the hash.
  • After completing the above steps, print the value of count as the result.

Below is the implementation of the above approach:

C++




// C ++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to count substrings having
// even frequency of each character
int subString(string s, int n)
{
 
    // Stores the count of a character
    map<int, int> hash;
    hash[0] = 1;
 
    // Stores bitmask
    int pre = 0;
 
    // Stores the count of substrings
    // with even count of each character
    int count = 0;
 
    // Traverse the string S
    for (int i = 0; i < n; i++) {
 
        // Flip the ord(i)-97 bits in pre
        pre ^= (1 << int(s[i]) - 97);
 
        // Increment the count by hash[pre]
        count += hash[pre];
 
        // Increment count of pre in hash
        hash[pre] = hash[pre] + 1;
    }
 
    // Return the total count obtained
    return count;
}
 
// Driver Code
int main()
{
    string S = "abbaa";
    int N = S.length();
    cout << (subString(S, N));
}
 
// THIS CODE IS CONTRIBUTED BY UKASP.

Java




// Java program for the above approach
import java.util.*;
import java.lang.*;
 
class GFG{
     
// Function to count substrings having
// even frequency of each character
static int subString(String s, int n)
{
     
    // Stores the count of a character
    Map<Integer, Integer> hash = new HashMap<>();
    hash.put(0, 1);
 
    // Stores bitmask
    int pre = 0;
 
    // Stores the count of substrings
    // with even count of each character
    int count = 0;
 
    // Traverse the string S
    for(int i = 0; i < n; i++)
    {
         
        // Flip the ord(i)-97 bits in pre
        pre ^= (1 << (int)(s.charAt(i) - 97));
 
        // Increment the count by hash[pre]
        count += hash.getOrDefault(pre, 0);
 
        // Increment count of pre in hash
        hash.put(pre, hash.getOrDefault(pre, 0) + 1);
    }
 
    // Return the total count obtained
    return count;
}
 
// Driver code
public static void main(String[] args)
{
    String S = "abbaa";
    int N = S.length();
     
    System.out.print(subString(S, N));
}
}
 
// This code is contributed by offbeat

Python3




# Python program for the above approach
 
# Function to count substrings having
# even frequency of each character
def subString(s, n):
 
    # Stores the count of a character
    hash = {0: 1}
 
    # Stores bitmask
    pre = 0
 
    # Stores the count of substrings
    # with even count of each character
    count = 0
 
    # Traverse the string S
    for i in s:
       
        # Flip the ord(i)-97 bits in pre
        pre ^= (1 << ord(i) - 97)
 
        # Increment the count by hash[pre]
        count += hash.get(pre, 0)
 
        # Increment count of pre in hash
        hash[pre] = hash.get(pre, 0) + 1
         
    # Return the total count obtained
    return count
 
 
# Driver Code
 
S = "abbaa"
N = len(S)
print(subString(S, N))

C#




// C# program for the above approach
using System.IO;
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to count substrings having
// even frequency of each character
static int subString(string s, int n)
{
     
    // Stores the count of a character
    Dictionary<int,
               int> hash = new Dictionary<int,
                                          int>();
 
    hash[0] = 1;
 
    // Stores bitmask
    int pre = 0;
 
    // Stores the count of substrings
    // with even count of each character
    int count = 0;
 
    // Traverse the string S
    for(int i = 0; i < n; i++)
    {
         
        // Flip the ord(i)-97 bits in pre
        pre ^= (1 << (int)(s[i]) - 97);
 
        // Increment the count by hash[pre]
        if (hash.ContainsKey(pre))
            count += hash[pre];
        else
            count += 0;
 
        // Increment count of pre in hash
        if (hash.ContainsKey(pre))
            hash[pre] = hash[pre] + 1;
        else
            hash.Add(pre, 1);
    }
 
    // Return the total count obtained
    return count;
}
 
// Driver code
static void Main()
{
    String S = "abbaa";
    int N = S.Length;
     
    Console.WriteLine(subString(S, N));
}
}
 
// This code is contributed by sk944795
Output: 
4

 

Time Complexity: O(N)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer Geeks Classes Live 




My Personal Notes arrow_drop_up
Recommended Articles
Page :