Count Substrings With K-Frequency Characters I - 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 non-empty sequence of characters within a string.

Input & Output

Example 1 — Basic Case
$ Input: s = "abccc", k = 3
Output: 6
💡 Note: Substrings with at least one character appearing ≥3 times: "ccc", "cccc", "bccc", "bcccc", "abccc", "abcccc". The character 'c' appears 3+ times in each.
Example 2 — No Valid Substrings
$ Input: s = "aaab", k = 4
Output: 0
💡 Note: No character appears 4 or more times in any substring. Maximum frequency is 3 for 'a' in "aaab".
Example 3 — Single Character
$ Input: s = "aaaa", k = 2
Output: 9
💡 Note: All substrings of length ≥2 are valid: "aa"(×3), "aaa"(×2), "aaaa"(×1), plus longer ones starting from different positions. Total: 9 substrings.

Constraints

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

Visualization

Tap to expand
Count Substrings With K-Frequency Charactersabccc01234Input: s = "abccc", k = 3Character "c" appears 3+ times (highlighted in green)Valid substrings:"ccc", "cccc", "bccc", "bcccc", "abccc", "abcccc"Output: 6 substrings
Understanding the Visualization
1
Input
String s="abccc" and threshold k=3
2
Process
Find all substrings where at least one character appears ≥k times
3
Output
Count of valid substrings: 6
Key Takeaway
🎯 Key Insight: Count character frequencies incrementally to avoid redundant recalculation
Asked in
Google 15 Amazon 12 Microsoft 8
8.5K Views
Medium Frequency
~25 min Avg. Time
234 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