Talentd
FleetCode

3329. Count Substrings With K-Frequency Characters II

Hard72.2% acceptancePremium elsewhere, free here

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.

Example 1:

Input: s = "abacb", k = 2

Output: 4

Explanation:

The valid substrings are:

  • "aba" (character 'a' appears 2 times).
  • "abac" (character 'a' appears 2 times).
  • "abacb" (character 'a' appears 2 times).
  • "bacb" (character 'b' appears 2 times).

Example 2:

Input: s = "abcde", k = 1

Output: 15

Explanation:

All substrings are valid because every character appears at least once.

Constraints:

  • 1 <= s.length <= 3 * 105
  • 1 <= k <= s.length
  • s consists only of lowercase English letters.

Hints open one at a time

Hint 1
If substring [i, j] is valid, then for all k >= j, [i, k] is valid too.
Hint 2
For each i, find j with a sliding window or binary search.
0:48
Still stuck?Read the written solution, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def solve(self):
3 pass
4
Starter codePython 3Spaces: 4
Examples
Input
"abacb"
2
Input
"abcde"
1
Your code is saved on this device.Solution