Count Number of Homogenous Substrings

medium string counting math

Problem

A string is homogenous if all of its characters are the same. Given a string s, return the number of homogenous (contiguous) substrings of s. Because the count can be huge, return it modulo 109 + 7.

Inputs = "abbcccaa"
Output13
The runs are a, bb, ccc, aa. A run of length L contributes L·(L+1)/2 substrings: 1 + 3 + 6 + 3 = 13.
Inputs = "zzzzz"
Output15
One run of length 5 gives 5·6/2 = 15 homogenous substrings.

def count_homogenous(s):
    MOD = 10**9 + 7
    total = 0
    run = 0
    prev = ""
    for ch in s:
        if ch == prev:
            run += 1
        else:
            run = 1
        total = (total + run) % MOD
        prev = ch
    return total
function countHomogenous(s) {
  const MOD = 1000000007;
  let total = 0;
  let run = 0;
  let prev = "";
  for (const ch of s) {
    if (ch === prev) run += 1;
    else run = 1;
    total = (total + run) % MOD;
    prev = ch;
  }
  return total;
}
int countHomogenous(String s) {
    final int MOD = 1000000007;
    long total = 0;
    long run = 0;
    char prev = 0;
    for (int i = 0; i < s.length(); i++) {
        char ch = s.charAt(i);
        if (ch == prev) run += 1;
        else run = 1;
        total = (total + run) % MOD;
        prev = ch;
    }
    return (int) total;
}
int countHomogenous(string s) {
    const long long MOD = 1000000007;
    long long total = 0;
    long long run = 0;
    char prev = 0;
    for (char ch : s) {
        if (ch == prev) run += 1;
        else run = 1;
        total = (total + run) % MOD;
        prev = ch;
    }
    return (int) total;
}
Time: O(n) Space: O(1)