#2947
Count Beautiful Substrings I
MediumHash TableMathStringEnumerationNumber TheoryPrefix SumHash MapPrefix Sum
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach uses prefix sums and a hash map to efficiently count beautiful substrings without generating all possible substrings. This reduces the time complexity significantly.
⚙️
Algorithm
6 steps- 1Step 1: Initialize a hash map to store the frequency of (vowel_count - consonant_count, product_mod_k) pairs.
- 2Step 2: Initialize variables for vowel and consonant counts and a result counter.
- 3Step 3: Loop through the string while updating vowel and consonant counts.
- 4Step 4: For each character, calculate the difference between vowel and consonant counts and the product modulo k.
- 5Step 5: Check if this pair exists in the hash map. If it does, add its frequency to the result.
- 6Step 6: Update the hash map with the current pair.
solution.py17 lines
1def count_beautiful_substrings(s, k):
2 vowels = 'aeiou'
3 count = 0
4 n = len(s)
5 freq_map = {}
6 v_count, c_count = 0, 0
7 freq_map[(0, 1)] = 1 # Base case for empty substring
8 for char in s:
9 if char in vowels:
10 v_count += 1
11 else:
12 c_count += 1
13 product_mod_k = (v_count * c_count) % k
14 key = (v_count - c_count, product_mod_k)
15 count += freq_map.get(key, 0)
16 freq_map[key] = freq_map.get(key, 0) + 1
17 return countℹ
Complexity note: The time complexity is O(n) because we make a single pass through the string, and the space complexity is O(n) due to the hash map storing the frequency of pairs.
- 1Understanding the conditions for a beautiful substring is crucial to solving the problem efficiently.
- 2Using a hash map to store intermediate results can significantly reduce time complexity.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.