Vowels of All Substrings - Problem

Imagine you're a linguist analyzing the vowel density of every possible phrase within a word. Your task is to calculate the total sum of vowels across all possible substrings of a given word.

A substring is any contiguous sequence of characters within the string. For example, the word "abc" has substrings: "a", "b", "c", "ab", "bc", and "abc".

The vowels we're counting are: 'a', 'e', 'i', 'o', 'u' (case-sensitive).

Goal: Return the sum of vowel counts in every substring of the input word.

Note: Due to large constraints, use 64-bit integers to avoid overflow.

Input & Output

example_1.py โ€” Basic Case
$ Input: word = "aba"
โ€บ Output: 6
๐Ÿ’ก Note: The substrings are "a", "b", "a", "ab", "ba", "aba". Vowel counts: 1+0+1+1+1+2 = 6
example_2.py โ€” All Vowels
$ Input: word = "abc"
โ€บ Output: 3
๐Ÿ’ก Note: The substrings are "a", "b", "c", "ab", "bc", "abc". Vowel counts: 1+0+0+1+0+1 = 3
example_3.py โ€” Single Character
$ Input: word = "a"
โ€บ Output: 1
๐Ÿ’ก Note: Only one substring "a" which contains 1 vowel

Visualization

Tap to expand
The Echo Chamber: Vowel Contribution AnalysisEach vowel creates 'echoes' (appears in substrings) based on positionWord: "aeo"apos 0(0+1)ร—(3-0)=3epos 1(1+1)ร—(3-1)=4opos 2(2+1)ร—(3-2)=3Echo Pattern (Substrings containing each vowel):'a' echoes in:"a", "ae", "aeo" โ†’ 3 substrings'e' echoes in:"e", "ae", "eo", "aeo" โ†’ 4 substrings'o' echoes in:"o", "eo", "aeo" โ†’ 3 substringsTotal Echo Count: 3 + 4 + 3 = 10Computed in O(n) time, O(1) space!
Understanding the Visualization
1
Position Analysis
For each vowel, determine how many substrings can include it
2
Prefix Count
Count how many starting positions come before or at the vowel
3
Suffix Count
Count how many ending positions come at or after the vowel
4
Multiply
Total substrings containing the vowel = prefix ร— suffix
Key Takeaway
๐ŸŽฏ Key Insight: Instead of generating all substrings, we calculate how many times each vowel 'echoes' across all possible substrings using the mathematical formula (i+1) ร— (n-i) for position i.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single pass through the string, constant time calculation per character

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only using a few variables, no extra data structures needed

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค word.length โ‰ค 105
  • word consists of lowercase English letters only
  • Answer may exceed 32-bit integer range - use 64-bit integers
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
32.8K Views
Medium Frequency
~15 min Avg. Time
1.4K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen