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:

  1. Perfect Balance: The number of vowels equals the number of consonants
  2. 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.

Constraints

  • 1 โ‰ค s.length โ‰ค 1000
  • 1 โ‰ค k โ‰ค 1000
  • s consists of only lowercase English letters
  • Vowels are exactly: 'a', 'e', 'i', 'o', 'u'

Visualization

Tap to expand
๐ŸŽจ Beautiful Substring GalleryString: "baeyh" with k=2baeyh๐Ÿ”ด Consonants (Red) | ๐Ÿ”ต Vowels (Teal)Beautiful Substring: "aeyh"Vowels: 2 (a,e) | Consonants: 2 (y,h)Product: 2ร—2=4, Divisible by k=2 โœ“Beauty Conditions1. Equal vowels and consonants2. Product divisible by kโœ“ Both conditions satisfied๐ŸŽฏ Substring is Beautiful!
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!
Asked in
Google 25 Meta 18 Microsoft 12 Amazon 8
24.5K Views
Medium Frequency
~25 min Avg. Time
867 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen