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
Number of Wonderful Substrings: "aba" AnalysisabaInput StringWonderful Substrings:"a" (pos 0)"b" (pos 1)"a" (pos 2)"aba" (0-2)Not Wonderful:"ab" (0-1)"ba" (1-2)Frequency Analysis:✓ "a": a=1 (1 odd) → wonderful✗ "ab": a=1,b=1 (2 odd) → not wonderfulResult: 4 wonderful substrings
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
Asked in
Facebook 35 Google 28 Amazon 22
28.0K Views
Medium Frequency
~25 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen