You are given a string s and a positive integer k. Your task is to find all beautiful substrings within the given string.
A substring is considered beautiful if it satisfies both of the following conditions:
- Balance condition: The number of vowels equals the number of consonants
- Divisibility condition: The product of vowels and consonants is divisible by
k
In other words, if a substring has v vowels and c consonants, then:
v == c(v * c) % k == 0
Note: Vowels are 'a', 'e', 'i', 'o', 'u' (case-sensitive). All other letters are consonants.
Example: For string "aeiou" with k=2, the substring "ae" has 2 vowels and 0 consonants, so it's not balanced. The substring "ab" would have 1 vowel and 1 consonant, and 1*1=1 is not divisible by 2.
Return the total count of beautiful substrings in the given string.
Input & Output
Visualization
Time & Space Complexity
Single pass through string O(n), and for each position we check O(โk) possible remainders based on divisors of perfect squares
Hash map stores at most O(nโk) different (balance, remainder) combinations
Constraints
- 1 โค s.length โค 5 ร 104
- 1 โค k โค 1000
- s consists of only lowercase English letters
- Vowels are exactly 'a', 'e', 'i', 'o', 'u'
- All other lowercase letters are consonants