Number of Wonderful Substrings Problem
Description
LeetCode Problem 1915.
A wonderful string is a string where at most one letter appears an odd number of times.
- For example,
"ccjjc"and"abab"are wonderful, but"ab"is not.
Given a string word that consists of the first ten lowercase English letters ('a' through 'j'), return the number of wonderful non-empty substrings in word. If the same substring appears multiple times in word*, then count each occurrence separately.*
A substring is a contiguous sequence of characters in a string.
Example 1:
Input: word = "aba"
Output: 4
Explanation: The four wonderful substrings are underlined below:
- "aba" -> "a"
- "aba" -> "b"
- "aba" -> "a"
- "aba" -> "aba"
Example 2:
Input: word = "aabb"
Output: 9
Explanation: The nine wonderful substrings are underlined below:
- "aabb" -> "a"
- "aabb" -> "aa"
- "aabb" -> "aab"
- "aabb" -> "aabb"
- "aabb" -> "a"
- "aabb" -> "abb"
- "aabb" -> "b"
- "aabb" -> "bb"
- "aabb" -> "b"
Example 3:
Input: word = "he"
Output: 2
Explanation: The two wonderful substrings are underlined below:
- "he" -> "h"
- "he" -> "e"
Constraints:
1 <= word.length <= 10^5wordconsists of lowercase English letters from'a'to'j'.
Solution
Approach: Prefix Parity Mask + Counting
Only ten letters appear, so the parity of every letter's count in a prefix fits in a 10-bit mask: bit i is 1 when letter i has appeared an odd number of times.
A substring is the difference of two prefixes, and its parity mask is the XOR of the two prefix masks. The substring is wonderful when that XOR has at most one bit set. So for each prefix mask st we count earlier prefixes whose mask:
- equals
st(XOR is 0: every letter even), or - differs from
stin exactly one bit, i.e. equalsst ^ (1 << i)for someiin0..9.
Keep an array cnt of how many times each mask has appeared so far (start with cnt[0] = 1 for the empty prefix). For each character, flip its bit in st, add cnt[st] plus the ten cnt[st ^ (1 << i)] to the answer, then increment cnt[st]. The answer can exceed 32 bits, so use a 64-bit integer.
Complexity: O(10n) time and O(210) space.
from collections import defaultdict
class Solution:
def wonderfulSubstrings(self, word: str) -> int:
cnt = defaultdict(int)
cnt[0] = 1
ans = st = 0
for c in word:
st ^= 1 << (ord(c) - ord("a"))
ans += cnt[st]
ans += sum(cnt[st ^ (1 << i)] for i in range(10))
cnt[st] += 1
return ans