Vowels of All Substrings — LeetCode 2063 Python Solution
- Problem
- #2063
- Pattern
- Dynamic Programming
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given a string word, return the sum of the number of vowels ('a', 'e', 'i', 'o', and 'u') in every substring of word. A substring is a contiguous (non-empty) sequence of characters within a string.
Example
- Input
- word = "aba"
- Output
- 6
- Explanation
- All possible substrings are: "a", "ab", "aba", "b", "ba", and "a".
Python solution
class Solution:
def countVowels(self, word: str) -> int:
n = len(word)
return sum((i + 1) * (n - i) for i, c in enumerate(word) if c in 'aeiou')Complexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the string \textit{word} |
| Space | O(1) auxiliary |
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 2063. Vowels of All Substrings is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2063. Vowels of All Substrings?
- LeetCode 2063. Vowels of All Substrings is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2063. Vowels of All Substrings?
- The Python solution on this page runs in O(n), where n is the length of the string \textit{word}.
- What is the space complexity of LeetCode 2063. Vowels of All Substrings?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2063. Vowels of All Substrings cover?
- LeetCode 2063. Vowels of All Substrings is tagged Math, String, Dynamic Programming and Combinatorics on LeetCode.