Problem Description
Given a string s, count the number of homogenous substrings in s. A homogenous substring is defined as a substring where all characters are identical. Since the answer can be very large, return it modulo 10^9 + 7.
Key Insights
- A contiguous block (run) of identical characters of length n contributes n*(n+1)/2 homogenous substrings.
- Simply iterating through the string and counting the length of consecutive identical characters can give us each run length.
- Use modulo arithmetic at each step to handle large numbers.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the string s.
Space Complexity: O(1), as only a few additional variables are used.
Solution
The solution iterates over the string while maintaining a counter for the length of the current run of identical characters. When the character changes, it calculates the number of homogenous substrings from the run using the arithmetic series formula (n*(n+1)/2) and adds it to a running total. The modulo operation is applied to keep the result within the required range. This method efficiently calculates the total count by processing the string in a single pass.