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?- A. 5 1 6
- B. 5 0 6
- C. 4 1 0
- 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
- Problem: A 3 × 3 matrix has every row and column sorted ascending. Find the k-th smallest value by binary searching on the VALUE and…
- Problem: Each move removes either the leftmost or the rightmost box and subtracts its weight from x. Find the minimum moves to make x…
- Problem: A speech-analysis tool reports the maximum number of vowels in any window of exactly k consecutive letters. python def…
- Problem: Move all zero readings to the end of the array in place while keeping the order of the non-zero readings. python def…
- Problem: In a text editor '#' means backspace (on an empty buffer it does nothing). Compute the final text with a stack. python def…
- Problem: Normalise a Unix-style absolute path: collapse repeated slashes, drop '.', and let '..' go up one directory (never above root)…