Skip to content

3325. Count Substrings With K-Frequency Characters I 👍

  • Time: $O(n)$
  • Space: $O(26) = O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
 public:
  int numberOfSubstrings(string s, int k) {
    const int n = s.length();
    int ans = n * (n + 1) / 2;
    vector<int> count(26);

    for (int l = 0, r = 0; r < n; ++r) {
      const int c = s[r];
      ++count[c - 'a'];
      while (count[c - 'a'] == k)
        --count[s[l++] - 'a'];
      ans -= r - l + 1;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
  public int numberOfSubstrings(String s, int k) {
    final int n = s.length();
    int ans = n * (n + 1) / 2;
    int[] count = new int[26];

    for (int l = 0, r = 0; r < n; ++r) {
      final int c = s.charAt(r) - 'a';
      ++count[c];
      while (count[c] == k)
        --count[s.charAt(l++) - 'a'];
      ans -= r - l + 1;
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
  def numberOfSubstrings(self, s: str, k: int) -> int:
    n = len(s)
    ans = n * (n + 1) // 2
    count = collections.Counter()

    l = 0
    for r, c in enumerate(s):
      count[c] += 1
      while count[c] == k:
        count[s[l]] -= 1
        l += 1
      ans -= r - l + 1

    return ans