Vowels of All Substrings - 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.

Note: Due to the large constraints, the answer may not fit in a signed 32-bit integer. Please be careful during the calculations.

Input & Output

Example 1 — Basic Case
$ Input: word = "aba"
Output: 6
💡 Note: Substrings are: "a" (1 vowel), "ab" (1 vowel), "aba" (2 vowels), "b" (0 vowels), "ba" (1 vowel), "a" (1 vowel). Total: 1+1+2+0+1+1 = 6
Example 2 — No Vowels
$ Input: word = "abc"
Output: 3
💡 Note: Substrings are: "a" (1), "ab" (1), "abc" (1), "b" (0), "bc" (0), "c" (0). Total: 1+1+1+0+0+0 = 3
Example 3 — All Vowels
$ Input: word = "aei"
Output: 10
💡 Note: Each position contributes: a at pos 0: (0+1)*(3-0)=3, e at pos 1: (1+1)*(3-1)=4, i at pos 2: (2+1)*(3-2)=3. Total: 3+4+3 = 10

Constraints

  • 1 ≤ word.length ≤ 105
  • word consists of lowercase English letters only

Visualization

Tap to expand
Vowels of All Substrings INPUT word = "aba" a i=0 V b i=1 C a i=2 V = Vowel = Consonant All Substrings: "a" - 1 vowel "ab" - 1 vowel "aba" - 2 vowels "b" - 0 vowels "ba" - 1 vowel "a" - 1 vowel ALGORITHM STEPS 1 Count Contribution Each vowel at index i appears in (i+1) * (n-i) substrings 2 Formula Breakdown (i+1) = starts before/at i (n-i) = ends at/after i 3 Calculate Each Vowel i=0, 'a': (0+1)*(3-0)=3 i=1, 'b': not a vowel i=2, 'a': (2+1)*(3-2)=3 Total = 3 + 3 = 6 4 Sum All Contributions O(n) time complexity O(1) space complexity FINAL RESULT Sum of vowels in all substrings 6 Breakdown by Position: a[0]=3 b[1]=0 a[2]=3 3 + 0 + 3 = 6 Status: OK Matches expected output Output: 6 Key Insight: Instead of counting vowels in each substring (O(n^2)), count how many substrings each vowel appears in. A character at index i is part of (i+1) * (n-i) substrings. Only add this count if the character is a vowel. This reduces time from O(n^2) to O(n). Use 64-bit integers for large inputs to avoid overflow. TutorialsPoint - Vowels of All Substrings | Optimal Solution
Asked in
Google 35 Facebook 28 Amazon 22 Microsoft 18
28.5K Views
Medium Frequency
~15 min Avg. Time
892 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