1241. Two-Odd Letter Substrings
A cipher analyst studies a string s written with the letters a to j only. A substring is nearly balanced when at most two of the ten letters occur an odd number of times in it; letters that do not occur count as even. Substrings at different positions are counted separately, even if their text is equal.
Return the number of non-empty nearly balanced substrings as a long. Keep a 10-bit mask whose bit c says whether letter c has appeared an odd number of times so far. A substring is nearly balanced when the masks at its two ends are equal or differ in one or two bits, so for each end you can look up the 1 + 10 + 45 = 56 matching masks in a table of 1024 counters.
The intended solution runs in O(56 * n) time and O(1024) space.
Example 1
- Input:
- s = "abc"
- Output:
- 5
- Explanation:
Every substring qualifies except the whole string, which has three letters with odd counts.
Example 2
- Input:
- s = "aab"
- Output:
- 6
- Explanation:
All six substrings have at most two letters with an odd count.
Constraints
1 ≤ s.length ≤ 5 * 104
s consists of the letters a to j
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms
Expected complexity
- Time
- O(56 * n)
- Space
- O(1)