Count Number of Homogenous Substrings — LeetCode 1759 Python Solution

MediumMathString
Problem
#1759
Reading time
3 min

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 ans

Complexity

MeasureComplexity
TimeO(n) or O(1)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview