Number of Equal Count Substrings Problem
Description
LeetCode Problem 2067.
You are given a 0-indexed string s consisting of only lowercase English letters, and an integer count. A substring of s is said to be an equal count substring if, for each unique letter in the substring, it appears exactly count times in the substring.
Return the number of equal count substrings in s.
A substring is a contiguous non-empty sequence of characters within a string.
Example 1:
Input: s = "aaabcbbcc", count = 3
Output: 3
Explanation:
The substring that starts at index 0 and ends at index 2 is "aaa".
The letter 'a' in the substring appears exactly 3 times.
The substring that starts at index 3 and ends at index 8 is "bcbbcc".
The letters 'b' and 'c' in the substring appear exactly 3 times.
The substring that starts at index 0 and ends at index 8 is "aaabcbbcc".
The letters 'a', 'b', and 'c' in the substring appear exactly 3 times.
Example 2:
Input: s = "abcd", count = 2
Output: 0
Explanation:
The number of times each letter appears in s is less than count.
Therefore, no substrings in s are equal count substrings, so return 0.
Example 3:
Input: s = "a", count = 5
Output: 0
Explanation:
The number of times each letter appears in s is less than count.
Therefore, no substrings in s are equal count substrings, so return 0
Constraints:
1 <= s.length <= 3 * 10^41 <= count <= 3 * 10^4sconsists only of lowercase English letters.
Solution
Approach: Enumerate the letter count + sliding window
An equal count substring with i distinct letters has length exactly i * count. There are at most 26 values of i, so try each one with a window of that fixed length.
Slide the window over s while keeping the letter frequencies and t, the number of letters whose frequency in the window is exactly count. Update t whenever a frequency becomes count (add one) or moves away from count (subtract one). If t == i for the current window, every letter in it appears exactly count times and there are i of them, so add one to the answer.
Complexity: O(26 * n) time, since there are at most 26 window sizes and each pass is linear; O(26) space.
class Solution:
def equalCountSubstrings(self, s: str, count: int) -> int:
ans = 0
for i in range(1, 27):
k = i * count
if k > len(s):
break
cnt = Counter()
t = 0
for j, c in enumerate(s):
cnt[c] += 1
t += cnt[c] == count
t -= cnt[c] == count + 1
if j >= k:
cnt[s[j - k]] -= 1
t += cnt[s[j - k]] == count
t -= cnt[s[j - k]] == count - 1
ans += i == t
return ans