Count Beautiful Substrings I — LeetCode 2947 Python Solution
MediumHash TableMathStringEnumerationNumber TheoryPrefix Sum
- Problem
- #2947
- Pattern
- Prefix Sum
- Reading time
- 3 min
- Source
- leetcode.com
The 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.
Example
- Input
- s = "baeyh", k = 2
- Output
- 2
- Explanation
- There are 2 beautiful substrings in the given string.
Python solution
Python
class Solution:
def beautifulSubstrings(self, s: str, k: int) -> int:
n = len(s)
vs = set("aeiou")
ans = 0
for i in range(n):
vowels = 0
for j in range(i, n):
vowels += s[j] in vs
consonants = j - i + 1 - vowels
if vowels == consonants and vowels * consonants % k == 0:
ans += 1
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Prefix Sum
Precompute running totals once so any range query becomes a single subtraction. LeetCode 2947. Count Beautiful Substrings I is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.
The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2947. Count Beautiful Substrings I?
- LeetCode 2947. Count Beautiful Substrings I is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2947. Count Beautiful Substrings I?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2947. Count Beautiful Substrings I?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2947. Count Beautiful Substrings I cover?
- LeetCode 2947. Count Beautiful Substrings I is tagged Hash Table, Math, String, Enumeration, Number Theory and Prefix Sum on LeetCode.