Number of Wonderful Substrings - 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.
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.
Input & Output
Example 1 — Basic Wonderful String
$
Input:
word = "aba"
›
Output:
4
💡 Note:
Four wonderful substrings: "a" (index 0), "b" (index 1), "a" (index 2), and "aba" (indices 0-2). All single characters are wonderful, and "aba" has 'a' appearing 2 times (even) and 'b' appearing 1 time (odd) - at most one odd count.
Example 2 — All Single Characters
$
Input:
word = "aabb"
›
Output:
9
💡 Note:
Single character substrings: "a", "a", "b", "b" (4 total). Two character substrings: "aa", "ab", "bb" (3 total). Three character: "aab", "abb" (2 total). Four character: "aabb" (1 total). Total: 4+3+2+0 = 9 wonderful substrings.
Example 3 — No Wonderful Multi-Character Substrings
$
Input:
word = "he"
›
Output:
2
💡 Note:
Only the single character substrings "h" and "e" are wonderful. The substring "he" has both characters appearing once (2 odd counts > 1), so it's not wonderful.
Constraints
- 1 ≤ word.length ≤ 105
- word consists of lowercase English letters from 'a' to 'j'
Visualization
Tap to expand
Understanding the Visualization
1
Input Analysis
String "aba" with characters from a-j
2
Substring Generation
Find all contiguous substrings and check frequency patterns
3
Wonderful Check
Count substrings with ≤1 character having odd frequency
Key Takeaway
🎯 Key Insight: Use bitmasks to efficiently track character frequency parity and count wonderful substrings in O(n) time
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code