# 21. Count Number of Homogenous Substrings

Given a string `s`, return *the number of **homogenous** substrings of* `s`*.* Since the answer may be too large, return it **modulo** `109 + 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.

```
Example 1:
Input: s = "abbcccaa"
Output: 13
Explanation: The homogenous substrings are listed as below:
"a"   appears 3 times.
"aa"  appears 1 time.
"b"   appears 2 times.
"bb"  appears 1 time.
"c"   appears 3 times.
"cc"  appears 2 times.
"ccc" appears 1 time.
3 + 1 + 2 + 1 + 3 + 2 + 1 = 13.

Example 2:
Input: s = "xy"
Output: 2
Explanation: The homogenous substrings are "x" and "y".


Example 3:
Input: s = "zzzzz"
Output: 15
```

## Solution:&#x20;

**Approach:**\
**No of substring of  a string n:- (Σn = n \* (n+1)/2 )**\
**We would find the length of homogeneous substring and count no ways possible**&#x20;

```cpp
class Solution
{
public:
    int countHomogenous(string s)
    {

        int mod = 1000000007;
        long long int count = 0;

        int n = s.length();

        int i = 0;
        int j = 1;

        while (i < n)
        {

            while (s[i] == s[j] && j < n)
            {
                j++;
            }

            long long int len = j - i;
            long long int ways = (len * (len + 1)) / 2;
            count += ways;
            i = j;
            j++;
        }

        return count % mod;
    }
};
```

**Time Complexity: O(n)**


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://soumyajit4419.gitbook.io/ds-algo/strings/21.-count-number-of-homogenous-substrings.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
