Vowels of All Substrings — LeetCode 2063 Python Solution

MediumMathStringDynamic ProgrammingCombinatorics
Problem
#2063
Reading time
2 min

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

Python
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

MeasureComplexity
TimeO(n), where n is the length of the string \textit{word}
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview