Number of Wonderful Substrings — LeetCode 1915 Python Solution

MediumBit ManipulationHash TableStringPrefix Sum
Problem
#1915
Pattern
Prefix Sum
Reading time
2 min

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 ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(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

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview