Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Find the longest substring in which each vowel a, e, i, o, u occurs an even number of times. A 5-bit parity mask of the prefix is stored at its first occurrence.

Problem: Find the longest substring in which each vowel a, e, i, o, u occurs an even number of times. A 5-bit parity mask of the prefix is stored at its first occurrence.
def even_vowels(s):
    pos = {0: -1}; mask = best = 0
    for i, ch in enumerate(s):
        k = "aeiou".find(ch)
        if k >= 0:
            mask ^= 1 << k
        if mask in pos:
            best = max(best, i - pos[mask])
        else:
            pos[mask] = i
    return best
print(even_vowels("banana"), even_vowels("education"), even_vowels("rhythm"))
What is printed?
  1. A. 5 1 6
  2. B. 5 0 6
  3. C. 4 1 0
  4. D. 6 1 6

Correct answer: A. 5 1 6

Two prefixes with the same parity mask enclose a substring where every vowel count is even, so remember the first index of each of the 32 masks. "banana": the mask returns to 0 after "banan" (two a's) → 5; the whole word has three a's. "education" uses each vowel once and every prefix mask is new after the first letter, so only a single consonant (length 1) qualifies. "rhythm" has no vowels → whole string, 6. O(n) time, O(32) space.

More Coding Interview Problems questions

Exams that ask this topic