Count Substrings With K-Frequency Characters II

Count substrings of s where at least one character appears at least k times — atLeast counting via sliding window.

Hard
Time O(n) Space O(1)
LeetCode
3 min read
sliding-window string hash-map

Problem#

Count substrings of s such that at least one character appears at least k times.

Examples#

  • s = "abacb", k = 24 ("aba", "abac", "abacb", "bacb")
  • s = "abcde", k = 115

Constraints#

  • 1 <= s.length <= 3 * 10^5, 1 <= k <= s.length.

Hints#

Hint 1
For each right, find the smallest left such that some character appears ≥ k times in [left..right]. All left' ≤ left work too.

Approach#

Track frequencies. Expand right; while some count reaches k, the window is valid. Advance left to record the smallest valid left for that right; all starts ≤ left produce valid substrings ending at right.

Solution#

Count Substrings With K-Frequency Characters II
class Solution {
public:
long long numberOfSubstrings(string s, int k) {
int count[26] = {0};
long long ans = 0;
int left = 0;
for (int right = 0; right < (int)s.size(); ++right) {
++count[s[right] - 'a'];
while (count[s[right] - 'a'] >= k) {
--count[s[left++] - 'a'];
}
ans += left;
}
return ans;
}
};

Editorial#

The slick observation: once the window first becomes valid at right, every shorter prefix start [0, left) still yields a valid substring ending at right. So ans += left counts them en bloc. We track only the character that just crossed k because that’s the only one whose count could have triggered validity.

Complexity#

  • Time: O(n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.