Input: S = “324425”
Explanation: Two substrings consisting of even frequent elements only are “44” and “2442”. Since “2442” is the longer of the two, print 4 as the required answer.
Input: S = “223015150”
Explanation: Three substrings consisting of even frequent elements only are “22”, “1515” and “015150”. Since “015150” is the longest among the three, print 4 as the required answer.
Naive Approach: The simplest approach is to generate all possible substrings of even length from the given string and for each substring, check if it contains characters with even frequencies only or not. Print the length of the longest of all such substrings.
Time Complexity: O(N3)
Auxiliary Space: O(N)
Efficient Approach: To optimize the above approach the idea is to use Bit Masking. Follow the steps below to solve the problem:
- Traverse the string from left to right.
- While traversing, use a bitmask variable, say mask, to keep track of the occurrence of each element from index 0 to the current index, whether it is even or odd. The ith (0 ≤ i ≤ 9) bit in the mask is 0 if the digit i has occurred even number of times up to the current index, and 1 if it has occurred an odd number of times.
- Use a variable val to store the value of digit present at the current index.
- To update the occurrence of val, take Bitwise XOR of mask with 1 << val.
- Use a Hash table ind to keep track of the index of each bitmask.
- After updating the value of mask at the current index, check if it is present in ind or not:
- If the value of the mask is already present in ind, it means that each element from index ind[mask] + 1 to current index occurs even number of times. Therefore, update the answer if the length of this segment from index ind[mask] + 1 to the current index is greater than the answer.
- Otherwise, assign the value of the current index to ind[mask].
- Finally, print the length of the required substring after completing the above steps.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(N)
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.