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
String Analysis: Finding Quality SubstringsValid SubstringsAt least one characterappears โ‰ฅ k timesInvalid SubstringsNO character appearsโ‰ฅ k timesComplementary CountingSliding Window Process1. Expand window โ†’ 2. Track frequencies โ†’ 3. Contract if max โ‰ฅ k โ†’ 4. Count substringsO(n)TimeO(1)SpaceOptimal Solution!
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.
Asked in
Google 42 Amazon 35 Microsoft 28 Meta 22
42.0K Views
High Frequency
~25 min Avg. Time
1.4K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen