1759. Count Number of Homogenous Substrings LeetCode Solution
In this guide, you will get 1759. Count Number of Homogenous Substrings LeetCode Solution with the best time and space complexity. The solution to Count Number of Homogenous Substrings problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Count Number of Homogenous Substrings solution in C++
- Count Number of Homogenous Substrings solution in Java
- Count Number of Homogenous Substrings solution in Python
- Additional Resources
Problem Statement of Count Number of Homogenous Substrings
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.
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.
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(1)
1759. Count Number of Homogenous Substrings LeetCode Solution in C++
class Solution {
public:
int countHomogenous(string s) {
constexpr int kMod = 1'000'000'007;
int ans = 0;
int count = 0;
char currentChar = '@';
for (const char c : s) {
count = c == currentChar ? count + 1 : 1;
currentChar = c;
ans += count;
ans %= kMod;
}
return ans;
}
};
/* code provided by PROGIEZ */
1759. Count Number of Homogenous Substrings LeetCode Solution in Java
class Solution {
public int countHomogenous(String s) {
final int kMod = 1_000_000_007;
int ans = 0;
int count = 0;
char currentChar = '@';
for (final char c : s.toCharArray()) {
count = c == currentChar ? count + 1 : 1;
currentChar = c;
ans += count;
ans %= kMod;
}
return ans;
}
}
// code provided by PROGIEZ
1759. Count Number of Homogenous Substrings LeetCode Solution in Python
class Solution:
def countHomogenous(self, s: str) -> int:
kMod = 1_000_000_007
ans = 0
count = 0
currentChar = '@'
for c in s:
count = count + 1 if c == currentChar else 1
currentChar = c
ans += count
ans %= kMod
return ans
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.