Count Number of Homogenous Substrings Problem
#1759
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1759.
Given a string s, return the number of homogenous substrings of s. Since the answer may be too large, return it modulo 10^9 + 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
Constraints:
1 <= s.length <= 10^5sconsists of lowercase letters.
Solution
Approach: Count Runs of Equal Characters
Split s into maximal runs of equal characters. A run of length c contains c * (c + 1) / 2 homogenous substrings, since every substring of the run is homogenous. Add these up over all runs, modulo 10^9 + 7.
Complexity: O(n) time and O(1) space.
class Solution:
def countHomogenous(self, s: str) -> int:
mod = 10**9 + 7
i, n = 0, len(s)
ans = 0
while i < n:
j = i
while j < n and s[j] == s[i]:
j += 1
cnt = j - i
ans += (1 + cnt) * cnt // 2
ans %= mod
i = j
return ans