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

PythonServer Side ProgrammingProgramming

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

      • mask := mask XOR (2^vowels[s[i]])

    • 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}
      mask = 0
      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:
            prefix[mask] = i
         else:
            res = max(res, i − prefix[mask])
      return res
ob = Solution()
s = "anewcoffeepot"
print(ob.solve(s))

Input

"anewcoffeepot"

Output

10
raja
Published on 15-Dec-2020 12:35:45
Advertisements