Count Number of Homogenous Substrings - Problem
Count Number of Homogenous Substrings
Given a string
For example, in the string
Your task: Return the total count of all possible homogenous substrings. Since this number can be very large, return the result
Key insight: A contiguous sequence of
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
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
โ Linear Growth
Space Complexity
O(1)
Only using a few variables to track current state, no additional data structures needed
โ Linear Space
Constraints
- 1 โค s.length โค 105
- s consists of lowercase English letters only
- Return result modulo 109 + 7
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code