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).
Examples:
Input: S = “abbbcc”
Output: ODD
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”
Output: EVEN
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.
C++
// C++ code to implement the above approach #include <bits/stdc++.h>using namespace std; // Function to find the parity// of the required charactersstring oddEven(string S){ // Array to store frequency of each character int hash[27] = { 0 }; int x = 0, y = 0; for (int i = 0; i < S.size(); i++) { hash[S[i] - 'a' + 1]++; } // Traversing on hash array for (int i = 1; i < 26; i++) { if (hash[i] != 0) { if (i % 2 == 0 && hash[i] % 2 == 0) x++; else if (i % 2 == 1 && hash[i] % 2 == 1) y++; } } if ((x + y) % 2 == 1) return "ODD"; else return "EVEN";} // Driver codeint main(){ string S = "abbbcc"; // Function call cout << oddEven(S); return 0;} |
ODD
Time Complexity: O(|S|) where |S| is the size of string S.
Space Complexity: O(1)


.png)