Count Substrings With K-Frequency Characters II - Problem

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.

A substring is a contiguous sequence of characters within a string.

Input & Output

Example 1 — Basic Case
$ Input: s = "abcb", k = 2
Output: 5
💡 Note: Substrings with at least one character appearing ≥ 2 times: "cb" (b appears 1 time - invalid), "bcb" (b appears 2 times), "abcb" (b appears 2 times), etc. Total count is 5.
Example 2 — No Valid Substrings
$ Input: s = "abc", k = 2
Output: 0
💡 Note: No character appears 2 or more times in any substring, so result is 0.
Example 3 — All Same Characters
$ Input: s = "aaaa", k = 2
Output: 9
💡 Note: All substrings of length ≥ 2 are valid: "aa", "aa", "aa", "aaa", "aaa", "aaaa", plus 3 more "aa" patterns. Total = 9.

Constraints

  • 1 ≤ s.length ≤ 104
  • 1 ≤ k ≤ s.length
  • s consists of only lowercase English letters

Visualization

Tap to expand
Count Substrings With K-Frequency CharactersInput: s = "abcb", k = 2abcbFind substrings where at least one character appears ≥ 2 timesValid substrings:"bcb" (b appears 2 times), "abcb" (b appears 2 times), etc.Output: 5Total count of valid substrings
Understanding the Visualization
1
Input
String s and frequency threshold k
2
Process
Find substrings where ≥1 character appears ≥k times
3
Output
Count of valid substrings
Key Takeaway
🎯 Key Insight: Use complement counting - total substrings minus those with no frequent characters
Asked in
Google 15 Microsoft 12 Amazon 8
23.0K Views
Medium Frequency
~25 min Avg. Time
890 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