Homogenous Substrings and Gauss

Interesting that this problem actually gets a help from Gauss' formula for summation of consecutive numbers (you know, the one that he taught his teacher when he was only 10... check it out: Gauss_addition_lesson.pdf (hawaii.edu)). Here it is: Count Number of Homogenous Substrings - LeetCode

1759. Count Number of Homogenous Substrings
Medium

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.

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 <= 105
  • s consists of lowercase letters.
Accepted
5,622
Submissions
14,465

The interesting thing to notice is that given a fully homogenous string such as "aaa", there are 3 + 2 + 1 homogeneous substrings, hence what you want to do is given a fully homogeneous string of size N, the number of homogeneous substrings will be 1+2+3+...+N, that's when Gauss comes into the picture and you can replace that with N*(N+1)/2. That can be done then with one scan and no additional space. Code is down below, cheers and happy Snow Day, ACC.


public int CountHomogenous(string s)
{
    if (String.IsNullOrEmpty(s)) return 0;

    char currentChar = '*';
    long currentCount = 0;
    long retVal = 0;

    for (int i = 0; i < s.Length; i++)
    {
        if (s[i] == currentChar)
        {
            currentCount++;
        }
        else
        {
            retVal = (retVal + ((currentCount * (currentCount + 1)) / 2)) % 1000000007;
            currentChar = s[i];
            currentCount = 1;
        }
    }

    retVal = (retVal + ((currentCount * (currentCount + 1)) / 2)) % 1000000007;
    return (int)retVal;
}

Comments

Popular posts from this blog

Count Binary Substrings

Count Vowels Permutation: Standard DP

Maximum Number of Balloons