Number of substrings with each character occurring even times
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:
Python3
| 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 | 
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:
Python3
| 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 | 
Time Complexity: O(N)
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Original page link
Best Cool Tech Gadgets
Top favorite technology gadgets
 
 
 
 
0 comments:
Post a Comment