← Questions

Count redundant substrings by vowel and consonant weights

0
AmazonCoding

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 y always a consonant, as stated?
  • With a = 1 and b = 1, every substring counts: is the answer then n(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 - 1 and each consonant weight b - 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 = 1 and b = 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

strings · prefix sums · hash map

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding