Skip to main content
Back to problems
#1759
Medium Algorithms

Count number of homogenous substrings

Math String
57.4% acceptance
Feb 25, 2026
1586
104
Given a string s, return the number of homogenous substrings of s. Since the answer may be too large, return it modulo 10^9 + 7. A string is homogenous if all the characters of the string are the same. A substring is a contiguous sequence of characters within a string.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn count_homogenous(s: String) -> i32 {
    const MOD: i64 = 1_000_000_007;
    let s = s.as_bytes();
    let mut total: i64 = 0;
    let mut run = 1i64;
    for i in 1..s.len() {
      if s[i] == s[i - 1] {
        run += 1;
      } else {
        total = (total + run * (run + 1) / 2) % MOD;
        run = 1;
      }
    }
    total = (total + run * (run + 1) / 2) % MOD;
    total as i32
  }
}