Parity of count of letters whose position and frequency have same parity
Given a string S of lowercase English characters, find out whether the number of the letters whose frequencies in the string have the same parity as their positions in the English alphabet is odd or even (i.e., they have an odd frequency in the string and their position is at an odd number in the English alphabet or have even frequency and their position is at an even number in the English alphabet).
Input: S = “abbbcc”
Explanation: ‘a’ occupies 1st place(odd) in English alphabets and its frequency is odd(1),
‘b’ occupies 2nd place(even) but its frequency is odd(3) so it doesn’t get counted
‘c’ occupies 3rd place(odd) but its frequency is even(2) so it also doesn’t get counted.
Input: S = “nobitaa”
Approach: The problem can be solved following the below idea:
Store frequency of each character in a new array. Then traverse on that array. While traversing if position of element is even and its frequency is also even then increment or if position of element is odd and its frequency is also odd then increment the count and find the parity of the final count.
Follow the steps mentioned here to implement the idea:
- Create a hash array of size 27 (to store the frequencies of all the lowercase characters).
- Create variables x = 0 and y = 0.
- Traverse on a string and store frequency of each character( S[i] – ‘a’ + 1) in hash array.
- Traverse on hash array:
- If the frequency of the character is greater than 0 then check if the index is even and its frequency is also even then increment x,
- If the index is odd and its frequency is also odd then increment y.
- if x + y is even then return even. Otherwise, return odd.
Below is the implementation of the above approach.
Time Complexity: O(|S|) where |S| is the size of string S.
Space Complexity: O(1)