Count Number of Homogenous Substrings - Problem
Count Number of Homogenous Substrings

Given a string s, you need to count all homogenous substrings within it. A homogenous substring is one where all characters are identical.

For example, in the string "abbcccaa", substrings like "a", "bb", "ccc", and "aa" are homogenous, but "ab" or "bcc" are not.

Your task: Return the total count of all possible homogenous substrings. Since this number can be very large, return the result modulo 109 + 7.

Key insight: A contiguous sequence of n identical characters contributes n ร— (n + 1) / 2 homogenous substrings to the total count.

Input & Output

example_1.py โ€” Basic Case
$ Input: s = "abbcccaa"
โ€บ Output: 13
๐Ÿ’ก Note: Groups: 'a'(1), 'bb'(2), 'ccc'(3), 'aa'(2). Contributions: 1ร—2/2=1, 2ร—3/2=3, 3ร—4/2=6, 2ร—3/2=3. Total: 1+3+6+3=13
example_2.py โ€” Single Character
$ Input: s = "xy"
โ€บ Output: 2
๐Ÿ’ก Note: Each single character forms one homogenous substring: 'x' and 'y'. Total: 2
example_3.py โ€” All Same Characters
$ Input: s = "zzzzz"
โ€บ Output: 15
๐Ÿ’ก Note: All characters identical, so we have one group of size 5. Contribution: 5ร—6/2=15 homogenous substrings

Visualization

Tap to expand
a a a b b c c c cGroup: aaaSize: 3Contribution:3ร—4/2 = 6Group: bbSize: 2Contribution:2ร—3/2 = 3Group: ccccSize: 4Contribution:4ร—5/2 = 10Total: 6 + 3 + 10 = 19Time: O(n) | Space: O(1)Single pass scanMathematical formulaModulo arithmetic
Understanding the Visualization
1
Scan for Groups
Identify consecutive identical character sequences
2
Calculate Contributions
Apply mathematical formula to each group
3
Sum and Return
Add all contributions modulo 10^9+7
Key Takeaway
๐ŸŽฏ Key Insight: Transform O(nยณ) substring enumeration into O(n) group analysis using the mathematical property that n consecutive identical characters contribute exactly nร—(n+1)/2 homogenous substrings

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single pass through the string, each character processed exactly once

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only using a few variables to track current state, no additional data structures needed

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค s.length โ‰ค 105
  • s consists of lowercase English letters only
  • Return result modulo 109 + 7
Asked in
Amazon 45 Google 38 Meta 32 Microsoft 28
42.3K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen