Count Substrings With K-Frequency Characters II Problem
Description
LeetCode Problem 3329.
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 <= 3 * 10^51 <= k <= s.lengthsconsists only of lowercase English letters.
Solution
Approach: Sliding Window
Fix the right end r of a substring and keep a left pointer l so that the window s[l..r] is the longest one in which every letter appears fewer than k times. Keep the letter counts of the window in an array cnt.
When s[r] is added, only its count can reach k. While it does, drop the character at l and move l right. Afterwards the window s[l..r] has no letter k times, and s[l - 1..r] (if it exists) does. Extending a substring never lowers a count, so every start position before l also gives a valid substring ending at r. That is l valid substrings, so add l to the answer.
Complexity: O(n) time and O(26) space, where n is the length of s.
class Solution:
def numberOfSubstrings(self, s: str, k: int) -> int:
cnt = Counter()
ans = l = 0
for c in s:
cnt[c] += 1
while cnt[c] >= k:
cnt[s[l]] -= 1
l += 1
ans += l
return ans