1550. Odd Letter Longest Window

Medium3.5 points estimatedBitmaskPrefix SumHash TableString

A word-game designer wants the longest piece of the string s (a contiguous substring) that can be rearranged into a palindrome. A piece can be rearranged into a palindrome exactly when at most one letter occurs an odd number of times in it.

Return the length of the longest such substring. Since a single character always qualifies, the answer is at least 1.

Hint: keep a 10-bit parity mask of the prefix, where bit c flips each time letter c appears. A substring has at most one odd letter exactly when the parity masks at its two ends are equal or differ in one bit. Store the first index at which each mask appeared, and for every prefix check its own mask and the 10 masks one bit away.

Required complexity: O(10 * n) time and O(2^10) space.

Example 1

Input:
s = "aabbcd"
Output:
5
Explanation:

The prefix aabbc has only c with an odd count, so it can be rearranged into a palindrome; adding d makes two odd letters, so the answer is 5.

Example 2

Input:
s = "abcdefghij"
Output:
1
Explanation:

All ten letters are distinct, so only a single character qualifies and the answer is 1.

Constraints

1 ≤ s.length ≤ 2*105

s contains only 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 2,400 msC++ 600 msJava 1,200 msJavaScript 1,200 msTypeScript 1,200 ms

Expected complexity

Time
O(10 n)
Space
O(2^10)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…