You are given a string word
. A substring is a contiguous (non-empty) sequence of characters within the string. A vowel substring is a substring that consists only of vowels (a, e, i, o, u) and has all five vowels present at least once.
Write a function countVowelSubstrings(word: str) -> int
that returns the number of vowel substrings in word.
Here’s a Python solution implementing the above strategy:
def countVowelSubstrings(word: str) -> int:
vowels = set('aeiou')
total_count = 0
n = len(word)
for start in range(n):
if word[start] in vowels:
seen_vowels = set()
for end in range(start, n):
if word[end] in vowels:
seen_vowels.add(word[end])
if len(seen_vowels) == 5:
total_count += 1
else:
break
return total_count
for start in range(n)
):
n
times.for end in range(start, n)
):
n
times for each start.Overall, the worst-case time complexity is (O(n^2)), where n
is the length of the input string word
.
This solution should be efficient enough for typical constraints found in coding interview problems.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?