Problem Description
Given a string s and a positive integer k, count the number of non-empty substrings for which the number of vowels equals the number of consonants and the product (vowels * consonants) is divisible by k. Vowels are "a", "e", "i", "o", "u", and all other letters are considered consonants.
Key Insights
- Only substrings of even length can have an equal number of vowels and consonants.
- A brute force approach using two nested loops is acceptable given the maximum string length of 1000.
- Using prefix sum arrays for vowels and consonants can optimize the count retrieval for each substring.
- Checking the condition (vowels * consonants) % k == 0 must be done after confirming the counts are equal.
Space and Time Complexity
Time Complexity: O(n^2), where n is the length of the string, due to the nested iteration over all substrings. Space Complexity: O(n), for storing the prefix sum arrays of vowels and consonants.
Solution
We solve the problem by iterating over all possible substrings while maintaining counts of vowels and consonants. One efficient method is to precompute two prefix sum arrays: one for vowels and one for consonants. For any substring from index i to j, the number of vowels is computed as vowels[j] - vowels[i] and similarly for consonants. We then verify if the counts are equal and if their product is divisible by k.
If the string length is small (n ≤ 1000), iterating over all possible substrings (i.e., O(n^2)) is feasible.