MediumNo. 1915
Number of Wonderful Substrings — LeetCode 1915 Python Solution
- Pattern
- Prefix Sum
- Topics
- Bit Manipulation, Hash Table, String, Prefix Sum
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- word = "aba"
- Output
- 4
- Explanation
- The four wonderful substrings are underlined below:
Python solution
class Solution:
def wonderfulSubstrings(self, word: str) -> int:
cnt = Counter({0: 1})
ans = st = 0
for c in word:
st ^= 1 << (ord(c) - ord("a"))
ans += cnt[st]
for i in range(10):
ans += cnt[st ^ (1 << i)]
cnt[st] += 1
return ansComplexity
- Time
- O(n)
- Space · auxiliary
- O(n)
Pattern: Prefix Sum
Precompute running totals once so any range query becomes a single subtraction. LeetCode 1915. Number of Wonderful Substrings is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.
The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 1177 | Can Make Palindrome from Substring | Medium |
| 1371 | Find the Longest Substring Containing Vowels in Even Counts | Medium |
| 1930 | Unique Length-3 Palindromic Subsequences | Medium |
| 0187 | Repeated DNA Sequences | Medium |
| 0389 | Find the Difference | Easy |
| 0691 | Stickers to Spell Word | Hard |
Frequently asked questions
- How hard is LeetCode 1915. Number of Wonderful Substrings?
LeetCode 1915. Number of Wonderful Substrings is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1915. Number of Wonderful Substrings?
The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1915. Number of Wonderful Substrings?
The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1915. Number of Wonderful Substrings cover?
LeetCode 1915. Number of Wonderful Substrings is tagged Bit Manipulation, Hash Table, String and Prefix Sum on LeetCode.