Skip to main content
Back to problems
#3084
Medium Algorithms

Count substrings starting and ending with given character

Math String Counting
49.9% acceptance
Feb 25, 2026
148
9
You are given a string s and a character c. Return the total number of substrings of s that start and end with c.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn count_substrings(s: String, c: char) -> i64 {
    let cnt = s.chars().filter(|&ch| ch == c).count() as i64;
    // Substrings starting and ending with c: choose any 2 positions (or same), = cnt*(cnt+1)/2
    cnt * (cnt + 1) / 2
  }
}