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?- A. 2 1
- B. 3 1
- C. 3 0
- 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
- 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)…
- Problem: Find the minimum number of brackets to insert so that a string of '(' and ')' becomes balanced. python def minadd(s): open = add…
- Problem: Parcels 1..5 are pushed onto a loading stack in that order (pops may happen at any time). Decide whether a given pop order is…
- Problem: People queue at a single counter; person i wants t[i] tickets, buys one per second and, if still needing more, goes to the back…