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 INPUT word = "aba" a idx 0 b idx 1 a idx 2 All Substrings: "a" "b" "a" "ab" "ba" "aba" Wonderful: at most one letter appears odd number of times Use bitmask: each bit tracks odd/even count of letter ALGORITHM STEPS 1 Initialize mask=0, count[0]=1 result=0 2 For each char Toggle bit: mask ^= (1 << (c - 'a')) 3 Count same mask result += count[mask] (all even counts) 4 Count 1-bit diff For i in 0..9: result += count[mask^(1<<i)] Hash Map (count): 0:1 1:2 2:1 3:1 mask values after each char FINAL RESULT Wonderful Substrings Found: "a" a:1 (odd) OK "b" b:1 (odd) OK "a" a:1 (odd) OK "aba" a:2 b:1 OK "ab","ba" 2 odd Output: 4 Key Insight: Use bitmask to track parity (odd/even) of each letter count. A wonderful substring has either: 1) Same mask as a previous prefix (all letters have even count difference), or 2) Mask differs by exactly 1 bit (exactly one letter has odd count). Hash map stores mask frequencies. TutorialsPoint - Number of Wonderful Substrings | Hash Map Approach
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