Skip to content

2950. Number of Divisible Substrings 👍

  • Time: $O(9n) = O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
 public:
  int countDivisibleSubstrings(string word) {
    // Let f(c) = d, where d = 1, 2, ..., 9.
    // Rephrase the question to return the number of substrings that satisfy
    //    f(c1) + f(c2) + ... + f(ck) / k = avg
    // => f(c1) + f(c2) + ... + f(ck) - k * avg, where avg in [1, 9].
    int ans = 0;

    for (int avg = 1; avg <= 9; ++avg) {
      int prefix = 0;
      unordered_map<int, int> prefixCount{{0, 1}};
      for (const char c : word) {
        prefix += f(c) - avg;
        ans += prefixCount[prefix]++;
      }
    }

    return ans;
  }

 private:
  int f(char c) {
    return 9 - ('z' - c) / 3;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
  public int countDivisibleSubstrings(String word) {
    // Let f(c) = d, where d = 1, 2, ..., 9.
    // Rephrase the question to return the number of substrings that satisfy
    //    f(c1) + f(c2) + ... + f(ck) / k = avg
    // => f(c1) + f(c2) + ... + f(ck) - k * avg, where avg in [1, 9].
    int ans = 0;

    for (int avg = 1; avg <= 9; ++avg) {
      int prefix = 0;
      Map<Integer, Integer> prefixCount = new HashMap<>();
      prefixCount.put(0, 1);
      for (final char c : word.toCharArray()) {
        prefix += f(c) - avg;
        ans += prefixCount.getOrDefault(prefix, 0);
        prefixCount.merge(prefix, 1, Integer::sum);
      }
    }

    return ans;
  }

  private int f(char c) {
    return 9 - ('z' - c) / 3;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
  def countDivisibleSubstrings(self, word: str) -> int:
    # Let f(c) = d, where d = 1, 2, ..., 9.
    # Rephrase the question to return the number of substrings that satisfy
    #    f(c1) + f(c2) + ... + f(ck) // k = avg
    # => f(c1) + f(c2) + ... + f(ck) - k * avg, where avg in [1, 9].
    ans = 0

    def f(c: str) -> int:
      return 9 - (ord('z') - ord(c)) // 3

    for avg in range(1, 10):
      prefix = 0
      prefixCount = collections.Counter({0: 1})
      for c in word:
        prefix += f(c) - avg
        ans += prefixCount[prefix]
        prefixCount[prefix] += 1

    return ans