Count Substrings With K-Frequency Characters II - Problem
Imagine you're analyzing text patterns in a document search engine. You need to find all possible substrings where at least one character appears frequently enough to be considered "significant".
Given a string s and an integer k, your task is to count the total number of substrings where at least one character appears at least k times within that substring.
A substring is a contiguous sequence of characters within a string. For example, in the string "abc", the substrings are: "a", "b", "c", "ab", "bc", and "abc".
Goal: Return the count of all valid substrings that contain at least one character with frequency โฅ k.
Input & Output
example_1.py โ Basic Case
$
Input:
s = "aaabbc", k = 3
โบ
Output:
3
๐ก Note:
Valid substrings are: "aaa" (a appears 3 times), "aaab" (a appears 3 times), "aaabb" (a appears 3 times). All other substrings have no character appearing 3 or more times.
example_2.py โ No Valid Substrings
$
Input:
s = "abcde", k = 2
โบ
Output:
0
๐ก Note:
No substring has any character appearing 2 or more times since all characters are unique.
example_3.py โ All Substrings Valid
$
Input:
s = "aaa", k = 1
โบ
Output:
6
๐ก Note:
All 6 possible substrings ("a", "a", "a", "aa", "aa", "aaa") contain at least one character that appears โฅ 1 times.
Constraints
- 1 โค s.length โค 105
- 1 โค k โค s.length
- s consists of only lowercase English letters
- The answer will fit in a 32-bit signed integer
Visualization
Tap to expand
Understanding the Visualization
1
Calculate Total
Find total possible substrings: n*(n+1)/2
2
Track Invalid
Use sliding window to count substrings where max frequency < k
3
Expand Window
Add characters to window, update frequency counts
4
Contract When Needed
Shrink window when any character frequency reaches k
5
Subtract
Return total_substrings - invalid_substrings
Key Takeaway
๐ฏ Key Insight: Instead of checking each substring individually (O(nยณ)), we use complementary counting. By efficiently finding substrings where NO character appears k times using a sliding window, we solve the problem in optimal O(n) time.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code