Data Structures & AlgorithmsEasyAccenture · Cognizant coding round pattern

Problem: A speech-analysis tool reports the maximum number of vowels in any window of exactly k consecutive letters.

Problem: A speech-analysis tool reports the maximum number of vowels in any window of exactly k consecutive letters.
def max_vowels(s, k):
    V = set("aeiou")
    cur = sum(c in V for c in s[:k]); best = cur
    for i in range(k, len(s)):
        cur += (s[i] in V) - (s[i - k] in V)
        best = max(best, cur)
    return best
print(max_vowels("quietroutine", 4), max_vowels("strength", 3))
What is printed?
  1. A. 2 1
  2. B. 3 1
  3. C. 3 0
  4. D. 4 1

Correct answer: B. 3 1

Fixed-size sliding window: add the entering letter, subtract the leaving one. "quietroutine" with k = 4: windows such as "quie" and "outi" hold 3 vowels, and no window holds 4. "strength" has a single vowel, so the best window of 3 holds 1. O(n) instead of recounting each window (O(n·k)).

More Coding Interview Problems questions

Exams that ask this topic