The Count Beautiful Substrings II interview question is a "Hard" extension of the beautiful substrings problem. You need to count substrings where the number of vowels equals the number of consonants, and their product is divisible by k. With string lengths up to 10^5, an O(N^2) solution will time out. You must find an O(N) or O(N log N) approach.
Amazon uses this String interview pattern to test your ability to optimize complex counting problems using mathematical insights and frequency maps. It evaluates if you can simplify a multi-variable condition (vowels == consonants and product % k == 0) into a single coordinate in a Hash Map. It's a true test of algorithmic maturity.
The problem uses Prefix Sums and Hash Maps.
v be number of vowels and c be number of consonants. Condition v == c implies v - c = 0.x = v = c. The second condition is (x * x) % k == 0. This is equivalent to x^2 % k == 0.m such that if x is a multiple of m, then x^2 is a multiple of k.(v - c, v % m).(v - c) and v % m. The number of beautiful substrings ending here is the count of this key in the map.k = 4. We need x^2 % 4 == 0. This means x must be a multiple of 2. So m = 2.
balance = vowels - consonants.v_count = total_vowels % 2.(balance, v_count) in our Hash Map.(balance, v_count) in the map.k directly in the map key, which doesn't work because v doesn't have to be a multiple of k for v^2 to be a multiple of k.Practice finding the "minimum period" m for square divisibility. If k = p1^a1 * p2^a2..., then m is the product of pi ^ ceil(ai / 2). This is a useful number theory trick for "Hard" problems.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Count Beautiful Substrings I | Medium | Solve | |
| Number of Substrings With Fixed Ratio | Medium | Solve | |
| Sum of Largest Prime Substrings | Medium | Solve | |
| Fraction to Recurring Decimal | Medium | Solve | |
| Integer to Roman | Medium | Solve |