Count Number of Homogenous Substrings - 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.

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.

Input & Output

Example 1 — Basic Case
$ Input: s = "abbccc"
Output: 10
💡 Note: Groups: "a"(1), "bb"(3), "ccc"(6). Homogenous substrings: "a", "b", "b", "bb", "c", "c", "c", "cc", "cc", "ccc". Total = 1+3+6 = 10
Example 2 — All Same Characters
$ Input: s = "aaaa"
Output: 10
💡 Note: One group of 4 'a's. Using formula: 4*(4+1)/2 = 10 substrings: "a", "a", "a", "a", "aa", "aa", "aa", "aaa", "aaa", "aaaa"
Example 3 — All Different Characters
$ Input: s = "xy"
Output: 2
💡 Note: Two groups each of size 1: "x"(1) and "y"(1). Total = 1+1 = 2 homogenous substrings

Constraints

  • 1 ≤ s.length ≤ 105
  • s consists of lowercase English letters

Visualization

Tap to expand
Count Number of Homogenous Substrings INPUT String s = "abbccc" a b b c c c 0 1 2 3 4 5 Homogenous Groups: "a" - length 1 "bb" - length 2 "ccc" - length 3 s = "abbccc" Length: 6 characters ALGORITHM STEPS 1 Identify Groups Find consecutive same chars 2 Count Length n Get each group's length 3 Apply Formula Substrings = n*(n+1)/2 4 Sum All Groups Add all group counts Calculation: "a" n=1: 1*(1+1)/2 = 1 "bb" n=2: 2*(2+1)/2 = 3 "ccc" n=3: 3*(3+1)/2 = 6 Total = 1 + 3 + 6 = 10 FINAL RESULT All Homogenous Substrings: "a" 1 substring "b", "b", "bb" 3 substrings "c", "c", "c", "cc", "cc", "ccc" 6 substrings Output 10 OK - Answer verified mod 10^9+7 = 10 Key Insight: For a group of n consecutive identical characters, the number of homogenous substrings is n*(n+1)/2. This is the triangular number formula: count all substrings of length 1, 2, 3, ... n. Time Complexity: O(n) | Space Complexity: O(1) - Single pass through the string! TutorialsPoint - Count Number of Homogenous Substrings | Mathematical Approach - Count Groups
Asked in
Facebook 25 Amazon 20 Google 15
32.0K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen