Related Articles

# Length of the longest substring that contains even number of vowels

• Last Updated : 23 Jun, 2021

Given a string S consisting of N lowercase characters, the task is to find the length of the longest substring consisting of an even number of vowels.

Examples:

Input: S= “bcbcbc”
Output: 6
Explanation:
Consider the substring S[0, 5] i.e., “bcbcbc” is the longest substring because all vowels: a, e, i, o and u appear 0(which is even) number of times.

Input: S = “ebbaa”
Output: 4

Naive Approach: The simplest approach to solve the given problem is to generate all possible substrings from the given string S and for each substring, check if the frequency of all vowels in the substring is even or not. If found to be true, then update the maximum length of the string required. After checking for all the substrings, print the maximum length obtained.

Time Complexity: O(N2)
Auxiliary Space: O(1)

Efficient Approach: The above approach can also be optimized by using Hashing. The idea is to initialize a string, say temp of size 5 corresponding to the 5 vowels (a, e, i, o, u) with all 0s, where s[i] = 0 indicates that the ith vowel is occurring an even number of times. Now, traverse the given string and find the same state of the string, temp from the map and update the maximum length. Follow the steps below to solve the problem:

• Initialize a variable, say ans as 0 that stores the required result.
• Initialize a string, say temp of size 5 as “00000”.
• Create a hashmap, M to store the index of occurrence of string temp and initialize the value of temp in M as -1.
• Traverse the given string S over the range [0, N – 1] using the variable i and perform the following steps:
• If the character S[i] is a vowel, then update the string temp.
• If the string temp is present in the map M then store its value from the map M in a variable X and update the value of ans to the maximum of ans and (i – X).
• Otherwise, update the value of temp in the map M as i.
• After completing the above steps, print the value of ans as the result.

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach` `#include ``using` `namespace` `std;` `// Function to find the length of the``// longest substring having even number``// of vowels``int` `longestSubstring(string s)``{``    ``// Create two hashmaps``    ``unordered_map indexes;``    ``unordered_map<``char``, ``int``> chars(``        ``{ { ``'a'``, 0 }, { ``'e'``, 1 },``          ``{ ``'i'``, 2 }, { ``'o'``, 3 },``          ``{ ``'u'``, 4 } });` `    ``// Keep the track of frequencies``    ``// of the vowels``    ``string evenOdd = ``"00000"``;``    ``indexes[evenOdd] = -1;` `    ``// Stores the maximum length``    ``int` `length = 0;` `    ``// Traverse the given string S``    ``for` `(``int` `i = 0; i < s.size(); ++i) {` `        ``char` `c = s[i];` `        ``// Find character in the map``        ``auto` `it = chars.find(c);` `        ``// If it is a vowel, then update``        ``// the frequency``        ``if` `(it != chars.end()) {``            ``evenOdd[it->second]``                ``= evenOdd[it->second]``                          ``== ``'0'``                      ``? ``'1'``                      ``: ``'0'``;``        ``}` `        ``// Find the index of occurence``        ``// of the string evenOdd in map``        ``auto` `lastIndex = indexes.find(evenOdd);` `        ``if` `(lastIndex == indexes.end()) {``            ``indexes[evenOdd] = i;``        ``}` `        ``// Update the maximum length``        ``else` `{``            ``length = max(``                ``length, i - lastIndex->second);``        ``}``    ``}` `    ``// Print the maximum length``    ``cout << length;``}` `// Driver Code``int` `main()``{``    ``string S = ``"bcbcbc"``;``    ``longestSubstring(S);` `    ``return` `0;``}`

## Python3

 `# Python3 program for the above approach` `# Function to find the length of the``# longest substring having even number``# of vowels``def` `longestSubstring(s):``    ` `    ``# Create two hashmaps``    ``indexes ``=` `{}``    ``chars ``=` `{}``    ``chars[``'a'``] ``=` `0``    ``chars[``'e'``] ``=` `1``    ``chars[``'i'``] ``=` `2``    ``chars[``'o'``] ``=` `3``    ``chars[``'u'``] ``=` `4``    ` `    ``# Keep the track of frequencies``    ``# of the vowels``    ``evenOdd ``=` `"00000"``    ``evenOdd ``=` `[i ``for` `i ``in` `evenOdd]``    ``indexes["".join(evenOdd)] ``=` `-``1` `    ``# Stores the maximum length``    ``length ``=` `0` `    ``# Traverse the given string S``    ``for` `i ``in` `range``(``len``(s)):``        ``c ``=` `s[i]` `        ``# Find character in the map` `        ``# If it is a vowel, then update``        ``# the frequency``        ``if` `(c ``in` `chars):``            ``evenOdd[chars[it]] ``=` `'1'` `if` `evenOdd[chars[it]] ``else` `'0'``            ` `        ``# Find the index of occurence``        ``# of the string evenOdd in map``        ``if` `("".join(evenOdd) ``not` `in` `indexes):``            ``indexes["".join(evenOdd)] ``=` `i``            ` `        ``# Update the maximum length``        ``else``:``            ``length ``=` `max``(``                ``length, i ``-` `indexes["".join(evenOdd)])` `    ``# Print the maximum length``    ``print``(length)` `# Driver Code``if` `__name__ ``=``=` `'__main__'``:``    ` `    ``S ``=` `"bcbcbc"``    ` `    ``longestSubstring(S)` `# This code is contributed by mohit kumar 29`
Output:
`6`

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.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up