Count of substrings with the frequency of at most one character as Odd
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.
Input: S = “aba”
Explanation: The valid substrings are “a”, “b”, “a”, and “aba”. Therefore, the total number of required substrings are 4.
Explanation: The valid substrings are “a”, “aa”, “aab”, “aabb”, “a”, “abb”, “b”, “bb”, and “b”.
- The parity of the frequency of each character can be stored in a bitmask mask, where the ith character is represented by 2i. Initially the value of mask = 0.
- Create an unordered map seen, which stores the frequency of occurrence of each bitmask. Initially, the value of seen = 1.
- Create a variable cnt, which stores the count of the valid substrings. Initially, the value of cnt = 0.
- Iterate for each i in the range [0, N) and Bitwise XOR the value of the mask with the integer representing the ith character of the string and increment the value of cnt by seen[mask].
- For each valid i, Iterate through all characters in the range [a, z] and increase its frequency by flipping the jth set-bit in the current mask and increment the value of the cnt by the frequency of bitmask after flipping the jth set-bit.
- The value stored in cnt is the required answer.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(N)