3325. Count Substrings With K-Frequency Characters I LeetCode Solution
In this guide, you will get 3325. Count Substrings With K-Frequency Characters I LeetCode Solution with the best time and space complexity. The solution to Count Substrings With K-Frequency Characters I 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 Substrings With K-Frequency Characters I solution in C++
- Count Substrings With K-Frequency Characters I solution in Java
- Count Substrings With K-Frequency Characters I solution in Python
- Additional Resources
Problem Statement of Count Substrings With K-Frequency Characters I
Given a string s and an integer k, return the total number of substrings of s where at least one character appears at least k times.
Example 1:
Input: s = “abacb”, k = 2
Output: 4
Explanation:
The valid substrings are:
“aba” (character ‘a’ appears 2 times).
“abac” (character ‘a’ appears 2 times).
“abacb” (character ‘a’ appears 2 times).
“bacb” (character ‘b’ appears 2 times).
Example 2:
Input: s = “abcde”, k = 1
Output: 15
Explanation:
All substrings are valid because every character appears at least once.
Constraints:
1 <= s.length <= 3000
1 <= k <= s.length
s consists only of lowercase English letters.
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(26) = O(1)
3325. Count Substrings With K-Frequency Characters I LeetCode Solution in C++
class Solution {
public:
int numberOfSubstrings(string s, int k) {
const int n = s.length();
int ans = n * (n + 1) / 2;
vector<int> count(26);
for (int l = 0, r = 0; r < n; ++r) {
const int c = s[r];
++count[c - 'a'];
while (count[c - 'a'] == k)
--count[s[l++] - 'a'];
ans -= r - l + 1;
}
return ans;
}
};
/* code provided by PROGIEZ */
3325. Count Substrings With K-Frequency Characters I LeetCode Solution in Java
class Solution {
public int numberOfSubstrings(String s, int k) {
final int n = s.length();
int ans = n * (n + 1) / 2;
int[] count = new int[26];
for (int l = 0, r = 0; r < n; ++r) {
final int c = s.charAt(r) - 'a';
++count[c];
while (count[c] == k)
--count[s.charAt(l++) - 'a'];
ans -= r - l + 1;
}
return ans;
}
}
// code provided by PROGIEZ
3325. Count Substrings With K-Frequency Characters I LeetCode Solution in Python
class Solution:
def numberOfSubstrings(self, s: str, k: int) -> int:
n = len(s)
ans = n * (n + 1) // 2
count = collections.Counter()
l = 0
for r, c in enumerate(s):
count[c] += 1
while count[c] == k:
count[s[l]] -= 1
l += 1
ans -= r - l + 1
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.