Skip to content

1915. Number of Wonderful Substrings 👍

  • Time: $O(10n) = O(n)$
  • Space: $O(1024) = O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
 public:
  long long wonderfulSubstrings(string word) {
    long long ans = 0;
    int prefix = 0;           // the binary prefix
    vector<int> count(1024);  // the binary prefix count
    count[0] = 1;             // the empty string ""

    for (const char c : word) {
      prefix ^= 1 << c - 'a';
      // All the letters occur even number of times.
      ans += count[prefix];
      // ('a' + i) occurs odd number of times.
      for (int i = 0; i < 10; ++i)
        ans += count[prefix ^ 1 << i];
      ++count[prefix];
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
  public long wonderfulSubstrings(String word) {
    long ans = 0;
    int prefix = 0;              // the binary prefix
    int[] count = new int[1024]; // the binary prefix count
    count[0] = 1;                // the empty string ""

    for (final char c : word.toCharArray()) {
      prefix ^= 1 << c - 'a';
      // All the letters occur even number of times.
      ans += count[prefix];
      // ('a' + i) occurs odd number of times.
      for (int i = 0; i < 10; ++i)
        ans += count[prefix ^ 1 << i];
      ++count[prefix];
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def wonderfulSubstrings(self, word: str) -> int:
    ans = 0
    prefix = 0  # the binary prefix
    count = [0] * 1024  # the binary prefix count
    count[0] = 1  # the empty string ""

    for c in word:
      prefix ^= 1 << ord(c) - ord('a')
      # All the letters occur even number of times.
      ans += count[prefix]
      # `c` occurs odd number of times.
      ans += sum(count[prefix ^ 1 << i] for i in range(10))
      count[prefix] += 1

    return ans