Count Number of Homogenous Substrings — LeetCode 1759 Python Solution
MediumMathString
- Problem
- #1759
- Pattern
- Math and Number Theory
- Reading time
- 3 min
- Source
- leetcode.com
The 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.
Example
- Input
- s = "abbcccaa"
- Output
- 13
- Explanation
- The homogenous substrings are listed as below:
Python solution
Python
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) or O(1) |
| Space | O(1) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 1759. Count Number of Homogenous Substrings is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1759. Count Number of Homogenous Substrings?
- LeetCode 1759. Count Number of Homogenous Substrings is rated Medium on LeetCode.
- What topics does LeetCode 1759. Count Number of Homogenous Substrings cover?
- LeetCode 1759. Count Number of Homogenous Substrings is tagged Math and String on LeetCode.