#1759

Count Number of Homogenous Substrings

Medium
MathStringSliding WindowTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal approach leverages the fact that consecutive characters contribute to homogenous substrings in a predictable way. Instead of generating all substrings, we can count them directly based on the length of contiguous characters.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a counter for the total number of homogenous substrings and a variable to track the length of the current homogenous segment.
  2. 2Step 2: Iterate through the string, comparing each character with the previous one.
  3. 3Step 3: If they are the same, increment the length of the current segment. If not, reset the length to 1.
  4. 4Step 4: For each segment of length k, add k * (k + 1) / 2 to the total count.
  5. 5Step 5: Return the total count modulo 10^9 + 7.
solution.py13 lines
1# Full working Python code
2
3def countHomogenous(s):
4    count = 0
5    current_length = 1
6    mod = 10**9 + 7
7    for i in range(1, len(s)):
8        if s[i] == s[i - 1]:
9            current_length += 1
10        else:
11            current_length = 1
12        count = (count + current_length) % mod
13    return count

Complexity note: This complexity is linear because we are making a single pass through the string, counting segments without generating substrings.

  • 1Homogenous substrings can be counted based on the length of contiguous segments of the same character.
  • 2The formula for counting substrings from a segment of length k is k * (k + 1) / 2.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.