Count Substrings with even frequency of each character and one exception
Given a string S (‘a’ ≤ S[i] ≤ ‘t’) of length N (1 ≤ N ≤ 105), which consists of lowercase English alphabets, the task is to count all substrings such that the frequency of all characters should be even or all characters should occur an even number of times except any one character which might occur an odd number of times.
Input: S = “aab”
Explanation: The five valid substrings are underlined below:
“aab” -> “a”
“aab” -> “a”
“aab” -> “aa”
“aab” -> “b”
“aab” -> “aab”
Input: S = “abba”
An approach using Bitmasking:
The idea is to use Bitmasking technique, We’ll encode all visited character from 0 to ith index into our mask and add count of same mask that had occurred previously.
Follow the steps to implement the above idea:
- Create an array dp of size 2m where m is the distinct character in the given string [because there is this much possibility for any character to occur till any index]. dp[i] will Store the count of valid substrings having mask i
- Initialize dp = 1, as there is one possible way of the valid substring having mask 0 (i.e, if we don’t consider any character from the string).
- Iterate from i = 0 to N-1:
- Calculate the current mask at (S[i] – ‘a’) index.
- Add all the previous valid substrings that had the same mask
- Iterate from j = 0 to 20 for the current mask:
- Flip the jth bit of the current mask.
- Add all previous valid substrings having the same mask
- Increment the frequency of the current mask
- Return the result
Below is the implementation of the above approach:
Time Complexity: O(N), where n is the length of the given string
Auxiliary Space: O(2m), where m is the distinct character in the given string.
Please Login to comment...