Python coding

Longest stretch with even vowel counts

Given a string s of lowercase English letters, return the length of the longest substring in which each of the five vowels a, e, i, o and u appears an even number of times. Zero is even, so a stretch with no vowels at all counts. Return 0 when no non-empty substring qualifies (or s is empty).

Aim for one pass over s.

Besides the tests, one large input (a 4,831-letter string) with a ~100 ms limit (scaled to your device's speed): brute force won't pass.

  • longest_even_vowels("teatimecookie") → 10
  • longest_even_vowels("rhythm") → 6
  • longest_even_vowels("aeiou") → 0
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Only odd or even matters, so the vowel counts of a prefix fit in 5 bits: bit k is 1 when vowel k has appeared an odd number of times. Each vowel XORs its bit.

Hint 2

s[i+1..j] has every vowel even exactly when the prefixes ending at i and at j have the same mask: XOR cancels the part they share.

Hint 3

Store the first index of each mask, seeded with {0: -1} for the empty prefix. The longest stretch ending at j starts right after that first index.

Solution and why it works
pythonO(n) · O(1): at most 32 masks
def longest_even_vowels(s: str) -> int:
    bit = {v: 1 << i for i, v in enumerate("aeiou")}
    first = {0: -1}                  # parity mask -> first index whose prefix had it
    mask = best = 0
    for i, ch in enumerate(s):
        mask ^= bit.get(ch, 0)       # flip this vowel's odd/even bit
        if mask in first:
            best = max(best, i - first[mask])
        else:
            first[mask] = i
    return best

A prefix sum does not need sums: here the running value is a 5-bit mask of which vowels are odd so far, and XOR undoes itself, so a substring has every vowel even exactly when the masks at its two ends match. Keep only the first index of each mask, seeded {0: -1}: the longest stretch ending at j starts right after it. With 32 possible masks the map stays tiny. The trap is overwriting a stored index with a later one: it shortens the answer.