#2063

Vowels of All Substrings

Medium
MathStringDynamic ProgrammingCombinatoricsCombinatoricsDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

Instead of generating all substrings, we can calculate how many substrings each vowel contributes to. Each vowel at position i contributes to substrings that start from any index before or at i and end at any index after or at i.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a variable to keep track of the total vowel count.
  2. 2Step 2: Iterate through each character in the string. For each vowel found, calculate how many substrings it contributes to based on its position.
  3. 3Step 3: For a vowel at index i, it contributes to (i + 1) * (n - i) substrings, where n is the length of the string.
solution.py8 lines
1# Full working Python code
2word = 'aba'
3total_vowels = 0
4n = len(word)
5for i, char in enumerate(word):
6    if char in 'aeiou':
7        total_vowels += (i + 1) * (n - i)
8print(total_vowels)

Complexity note: The time complexity is O(n) because we only make a single pass through the string. The space complexity is O(1) since we are using a constant amount of extra space.

  • 1Each vowel's contribution can be calculated based on its position, avoiding the need to generate all substrings.
  • 2Understanding how many substrings a character contributes to is key to solving similar problems efficiently.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.