Number of Wonderful Substrings — LeetCode 1915 Python Solution
MediumBit ManipulationHash TableStringPrefix Sum
- Problem
- #1915
- Pattern
- 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
Python
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
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
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
LeetCode 1177Can Make Palindrome from SubstringMediumLeetCode 1371Find the Longest Substring Containing Vowels in Even CountsMediumLeetCode 1930Unique Length-3 Palindromic SubsequencesMediumLeetCode 187Repeated DNA SequencesMediumLeetCode 389Find the DifferenceEasyLeetCode 691Stickers to Spell WordHard
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.