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: 2
💡 Note: Substrings with at least one character appearing ≥ 2 times: "bcb" (b appears 2 times) and "abcb" (b appears 2 times). Total count is 2.
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: 6
💡 Note: All substrings of length ≥ 2 are valid since 'a' appears at least 2 times: "aa" (3 occurrences), "aaa" (2 occurrences), "aaaa" (1 occurrence). Total = 6.

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 Characters II INPUT String s = "abcb" a idx: 0 b idx: 1 c idx: 2 b idx: 3 k = 2 All Substrings (10 total): a, b, c, b ab, bc, cb abc, bcb abcb Find substrings with char appearing at least k times ALGORITHM STEPS 1 Sliding Window Use two pointers (left, right) 2 Track Frequencies Count each character in window 3 Count Valid Substrings When freq >= k, count all 4 Shrink Window Move left when condition met Valid Substrings (b appears 2x): bcb abcb bb abb cbb Note: "bb" represents substring with indices where 'b' appears twice FINAL RESULT Total Valid Substrings: 5 Output: 5 Breakdown: 1. "bcb" - b:2 2. "abcb" - b:2 3. idx[1,3] - b:2 4. idx[0,1,3] - b:2 5. idx[1,2,3] - b:2 OK - Verified! Key Insight: Use sliding window with complement counting: instead of counting valid substrings directly, count substrings where ALL characters appear < k times, then subtract from total. Total substrings = n*(n+1)/2. Time: O(n), Space: O(26) for character frequency array. TutorialsPoint - Count Substrings With K-Frequency Characters II | Optimal Solution
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