Count redundant substrings by vowel and consonant weights
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked at Amazon. It tests strings, prefix sums and hash map.
Write a function that counts the redundant substrings of a word.
A string s is redundant when its length equals a * V + b * C, where V is the number of vowels in s, C is the number of consonants in s, and a and b are given integers. The vowels are a, e, i, o, u; every other letter (including y) is a consonant.
def count_redundant_substrings(word: str, a: int, b: int) -> int: ...
Return how many of the n(n+1)/2 non-empty contiguous substrings of word are redundant. Substrings at different positions count separately, even if their text is the same.
Constraints
-
0 <= len(word) <= 10^5, lowercase English letters only. -
-10^5 <= a, b <= 10^5. - The answer can exceed 2^31.
Example 1
word = "code", a = 2, b = 0 -> 4
The rule becomes V + C = 2V, so V == C. The redundant substrings are "co", "od", "de" and "code".
Example 2
word = "queue", a = 1, b = 0 -> 10
The rule becomes V + C = V, so C == 0. Only substrings made entirely of vowels count, and "ueue" has 10 of them.
An O(n^2) solution is too slow for the largest inputs; aim for O(n).
Clarifying questions
- Is
yalways a consonant, as stated? - With
a = 1andb = 1, every substring counts: is the answer thenn(n+1)/2? - Should the answer be a Python int, since it can exceed 2^31?
What a strong answer covers
- Rewrites the rule: length is
V + C, so the condition is(a - 1) * V + (b - 1) * C = 0. - Gives each vowel weight
a - 1and each consonant weightb - 1; a substring is redundant when its weight sum is 0, so it counts pairs of equal prefix sums with a hash map in O(n). - Starts the prefix count with the empty prefix (sum 0), and notes the sums stay within about 10^10 at the limits.
- Handles
a = 1andb = 1(all substrings), the empty word (0), and words with only vowels or only consonants. - Tests both examples and checks against an O(n^2) brute force on random short words.
Follow-ups
- Return the longest redundant substring.
- Count substrings where the length is at most
a * V + b * C. - Answer many
(a, b)queries on the same word.
Where it's asked
What it tests
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
