Skip to main content
Back to problems
#2063
Medium Algorithms

Vowels of all substrings

Math String Dynamic Programming Combinatorics
55.2% acceptance
Feb 25, 2026
907
36
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.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn count_vowels(word: String) -> i64 {
    let is_vowel = |c: u8| matches!(c, b'a' | b'e' | b'i' | b'o' | b'u');
    let n = word.len() as i64;
    word.bytes().enumerate().filter(|(_, c)| is_vowel(*c)).map(|(i, _)| {
      let i = i as i64;
      // vowel at index i appears in substrings starting at 0..=i ending at i..=n-1
      // count = (i+1) * (n-i)
      (i + 1) * (n - i)
    }).sum()
  }
}