Skip to content

2067. Number of Equal Count Substrings 👍

  • Time: $O(26n) = 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
19
20
21
22
23
class Solution {
 public:
  int equalCountSubstrings(string s, int count) {
    const int maxUnique = unordered_set<int>(begin(s), end(s)).size();
    int ans = 0;

    for (int unique = 1; unique <= maxUnique; ++unique) {
      const int windowSize = unique * count;
      vector<int> lettersCount(26);
      int uniqueCount = 0;
      for (int i = 0; i < s.length(); ++i) {
        if (++lettersCount[s[i] - 'a'] == count)
          ++uniqueCount;
        if (i >= windowSize &&
            --lettersCount[s[i - windowSize] - 'a'] == count - 1)
          --uniqueCount;
        ans += uniqueCount == unique;
      }
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
  public int equalCountSubstrings(String s, int count) {
    final int maxUnique = s.chars().mapToObj(c -> (char) c).collect(Collectors.toSet()).size();
    int ans = 0;

    for (int unique = 1; unique <= maxUnique; ++unique) {
      final int windowSize = unique * count;
      int[] lettersCount = new int[26];
      int uniqueCount = 0;
      for (int i = 0; i < s.length(); ++i) {
        if (++lettersCount[s.charAt(i) - 'a'] == count)
          ++uniqueCount;
        if (i >= windowSize && --lettersCount[s.charAt(i - windowSize) - 'a'] == count - 1)
          --uniqueCount;
        ans += uniqueCount == unique ? 1 : 0;
      }
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
  def equalCountSubstrings(self, s: str, count: int) -> int:
    maxUnique = len(set(s))
    ans = 0

    for unique in range(1, maxUnique + 1):
      windowSize = unique * count
      lettersCount = Counter()
      uniqueCount = 0
      for i, c in enumerate(s):
        lettersCount[c] += 1
        if lettersCount[c] == count:
          uniqueCount += 1
        if i >= windowSize:
          lettersCount[s[i - windowSize]] -= 1
          if lettersCount[s[i - windowSize]] == count - 1:
            uniqueCount -= 1
        ans += uniqueCount == unique

    return ans
Back to top