Count Beautiful Substrings II - Problem

You are given a string s and a positive integer k.

Let vowels and consonants be the number of vowels and consonants in a string.

A string is beautiful if:

  • vowels == consonants
  • (vowels * consonants) % k == 0, which means the multiplication of vowels and consonants is divisible by k

Return the number of non-empty beautiful substrings in the given string s.

A substring is a contiguous sequence of characters in a string.

Vowel letters in English are 'a', 'e', 'i', 'o', and 'u'.

Consonant letters in English are every letter except vowels.

Input & Output

Example 1 — Basic Case
$ Input: s = "baeyh", k = 2
Output: 2
💡 Note: Beautiful substrings are "baey" (V=2, C=2, 2*2=4, 4%2=0) and "aey" (V=2, C=1... wait, this doesn't work). Actually: "ae" (V=2, C=0) fails balance. Let me recalculate: "ba" (V=1, C=1, 1*1=1, 1%2≠0), "bae" (V=2, C=1) fails balance. The beautiful substrings are "baey" (V=2, C=2, 2*2%2=0) and "aeyh" (V=2, C=2, 2*2%2=0).
Example 2 — Single Character
$ Input: s = "a", k = 1
Output: 0
💡 Note: Single vowel "a" has V=1, C=0, so vowels ≠ consonants. No beautiful substrings possible.
Example 3 — Minimum Beautiful
$ Input: s = "ab", k = 1
Output: 1
💡 Note: Substring "ab" has V=1, C=1 (balanced) and 1*1=1, 1%1=0 (divisible). This is beautiful.

Constraints

  • 1 ≤ s.length ≤ 5 × 104
  • 1 ≤ k ≤ 1000
  • s consists of only lowercase English letters

Visualization

Tap to expand
Count Beautiful Substrings II INPUT String s = "baeyh" b C a V e V y C h C V = Vowel C = Consonant Parameters s = "baeyh" k = 2 Beautiful Condition: vowels == consonants AND (v * c) % k == 0 ALGORITHM STEPS 1 Prefix Transform Track diff = vowels - consonants 2 Find Period Compute d = sqrt(k) factor 3 HashMap Counting Key: (diff, idx % d) 4 Count Pairs Same key pairs are valid Prefix Differences idx 0 1 2 3 4 5 char - b a e y h diff 0 -1 0 1 0 -1 i%2 0 1 0 1 0 1 (0,0) (0,0) (0,0) FINAL RESULT Beautiful Substrings Found: Substring 1: "ba" b a v=1, c=1: (1*1)%2=0 OK Substring 2: "aeyh" a e y h v=2, c=2: (2*2)%2=0 OK OUTPUT 2 2 beautiful substrings found Key Insight: For v*c to be divisible by k with v=c, we need v^2 % k = 0. Using number theory, we find the smallest period d where indices with same (prefix_diff, index % d) form valid pairs. This reduces O(n^2) to O(n). TutorialsPoint - Count Beautiful Substrings II | Optimized with Number Theory
Asked in
Google 25 Facebook 18 Amazon 15 Microsoft 12
12.5K Views
Medium Frequency
~35 min Avg. Time
284 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