#1915
Number of Wonderful Substrings
MediumHash TableStringBit ManipulationPrefix SumHash MapBit Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a bitmask to represent the frequency of characters, allowing us to efficiently check for wonderful substrings by leveraging previously computed results.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a HashMap to store the count of each bitmask configuration.
- 2Step 2: Iterate through the string, updating the bitmask based on character frequencies.
- 3Step 3: For each bitmask, check how many times it has occurred and how many times its neighbors (bitmask with one bit flipped) have occurred.
solution.py11 lines
1def wonderfulSubstrings(word):
2 count = 0
3 mask_count = {0: 1}
4 mask = 0
5 for char in word:
6 mask ^= 1 << (ord(char) - ord('a'))
7 count += mask_count.get(mask, 0)
8 for i in range(10):
9 count += mask_count.get(mask ^ (1 << i), 0)
10 mask_count[mask] = mask_count.get(mask, 0) + 1
11 return countℹ
Complexity note: The complexity is linear because we only traverse the string once and use a HashMap to store the counts, which allows for quick lookups.
- 1Using bit manipulation allows us to efficiently track character frequencies.
- 2HashMaps can be used to store previously seen states for quick lookups.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.