Count Beautiful Substrings I - Problem
π¨ Count Beautiful Substrings I
Imagine you're analyzing text patterns where balance and divisibility create beauty! You're given a string s and a positive integer k.
A substring is considered beautiful if it satisfies two elegant conditions:
- Perfect Balance: The number of vowels equals the number of consonants
- Divisibility Magic: The product of vowel count and consonant count is divisible by
k
Your mission: Count all non-empty beautiful substrings in the given string.
Note: Vowels are 'a', 'e', 'i', 'o', 'u' and consonants are all other letters.
Example: In string "baeyh" with k=2, the substring "baey" has 2 vowels ('a','e') and 2 consonants ('b','y'), so 2Γ2=4 which is divisible by 2. Beautiful! β¨
Input & Output
example_1.py β Basic Case
$
Input:
s = "baeyh", k = 2
βΊ
Output:
2
π‘ Note:
Beautiful substrings are "baey" (vowels=2, consonants=2, 2Γ2=4, 4%2=0) and "b" is not valid since it needs equal vowels and consonants. The substring "aeyh" gives vowels=2, consonants=2, and 2Γ2=4 which is divisible by 2.
example_2.py β Single Character
$
Input:
s = "abba", k = 1
βΊ
Output:
3
π‘ Note:
The beautiful substrings are: "ab" (V:1, C:1, 1Γ1=1, 1%1=0), "bb" is not valid (no vowels), "ba" (V:1, C:1, 1Γ1=1, 1%1=0), and "abba" (V:2, C:2, 2Γ2=4, 4%1=0). Total: 3 beautiful substrings.
example_3.py β Edge Case
$
Input:
s = "bcdf", k = 1
βΊ
Output:
0
π‘ Note:
All characters are consonants, so no substring can have equal vowels and consonants. Therefore, there are 0 beautiful substrings.
Visualization
Tap to expand
Understanding the Visualization
1
Identify Characters
Classify each letter as vowel (colorful) or consonant (grayscale)
2
Check Balance
Ensure equal number of vowels and consonants
3
Verify Divisibility
Confirm their product fits evenly into k-sized display cases
4
Count Beautiful
Increment counter for each valid arrangement
Key Takeaway
π― Key Insight: Transform the problem into finding balanced substrings where vowelΓconsonant products fit perfectly into k-sized containers!
Time & Space Complexity
Time Complexity
O(nΒ²)
Single pass through string, but checking divisibility condition still requires nested logic
β Quadratic Growth
Space Complexity
O(n)
Hash map to store prefix sum states
β‘ Linearithmic Space
Constraints
- 1 β€ s.length β€ 1000
- 1 β€ k β€ 1000
- s consists of only lowercase English letters
- Vowels are exactly: 'a', 'e', 'i', 'o', 'u'
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code