# Program to find length of longest substring with even vowel counts in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

Suppose we have a string s (lowercase), we have to find the length of the longest substring where each vowel occurs even number of times.

So, if the input is like s = "anewcoffeepot", then the output will be 10, as the substring "wcoffeepot" has two vowels "o" and "e", both of which occurs two times.

To solve this, we will follow these steps −

• vowels := a map assigning vowels and numeric values as {a:0, e:1, i:2, o:3, u:4}

• prefix := an empty map and insert a key-value pair (0, −1) into it

• mask := 0, n := size of s, res := 0

• for i in range 0 to n, do

• if s[i] is a vowels, then

• if mask is not in prefix, then

• prefix[mask] := i

• otherwise,

• res := maximum of res and (i − prefix[mask])

• return res

Let us see the following implementation to get better understanding −

## Example

Live Demo

class Solution:
def solve(self, s):
vowels = {"a": 0, "e": 1, "i": 2, "o": 3, "u": 4}
prefix = {0: −1}
n = len(s)
res = 0
for i in range(n):
if s[i] in vowels:
mask ^= 1 << vowels[s[i]]
if mask not in prefix:
else:
res = max(res, i − prefix[mask])
return res
ob = Solution()
s = "anewcoffeepot"
print(ob.solve(s))

## Input

"anewcoffeepot"

## Output

10
Updated on 15-Dec-2020 12:36:37