Count Number of Homogenous Substrings - Problem
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.
Input & Output
Example 1 — Basic Case
$
Input:
s = "abbccc"
›
Output:
10
💡 Note:
Groups: "a"(1), "bb"(3), "ccc"(6). Homogenous substrings: "a", "b", "b", "bb", "c", "c", "c", "cc", "ccc", "cccc". Total = 1+3+6 = 10
Example 2 — All Same Characters
$
Input:
s = "aaaa"
›
Output:
10
💡 Note:
One group of 4 'a's. Using formula: 4*(4+1)/2 = 10 substrings: "a", "a", "a", "a", "aa", "aa", "aa", "aaa", "aaa", "aaaa"
Example 3 — All Different Characters
$
Input:
s = "xy"
›
Output:
2
💡 Note:
Two groups each of size 1: "x"(1) and "y"(1). Total = 1+1 = 2 homogenous substrings
Constraints
- 1 ≤ s.length ≤ 105
- s consists of lowercase English letters
Visualization
Tap to expand
Understanding the Visualization
1
Input String
Given string with consecutive character groups
2
Identify Groups
Find consecutive same characters
3
Apply Formula
Calculate n*(n+1)/2 for each group and sum
Key Takeaway
🎯 Key Insight: Use the mathematical formula n*(n+1)/2 to count substrings in each consecutive group
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code