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: 3
💡 Note: Substrings with at least one character appearing ≥3 times: "ccc" (position 2-4), "bccc" (position 1-4), "abccc" (position 0-4). The character 'c' appears 3+ times in each. Total: 3 substrings.
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: 6
💡 Note: Substrings of length ≥2 where 'a' appears ≥2 times: "aa" appears 3 times (positions 0-1, 1-2, 2-3), "aaa" appears 2 times (positions 0-2, 1-3), "aaaa" appears 1 time (position 0-3). Total: 6 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 Characters INPUT String s = "abccc" a b c c c 0 1 2 3 4 k = 3 Valid Substrings: 1. "ccc" 2. "bccc" 3. "abccc" 4. "cccc" (overlap) 5. "bccc" (end) 6. "abccc" (end) All substrings where 'c' appears 3+ times ALGORITHM STEPS 1 Sliding Window Use two pointers: left, right 2 Track Frequency Count each char in window 3 Shrink Window When any char count >= k 4 Count Substrings Add (left + 1) to result Window Example: a b c c c Window [2,4]: c=3 (OK) Substrings: left+1 = 3 FINAL RESULT Counting all valid substrings: Right Window Add 0,1 c<3 0 2 c<3 0 3 c<3 0 4 c=3 (OK) +3 Continue shrinking... +3 Total: 6 Output 6 OK - 6 substrings found Each has char with count >= 3 Key Insight: Use sliding window to find the smallest valid window ending at each position. Once a character appears k times, ALL substrings starting from index 0 to left pointer are valid. This gives us (left + 1) valid substrings for each right position. Time: O(n), Space: O(26) for char frequency. TutorialsPoint - Count Substrings With K-Frequency Characters I | Optimal Sliding Window Approach
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