Find Longest Awesome Substring Problem
Description
LeetCode Problem 1542.
You are given a string s. An awesome substring is a non-empty substring of s such that we can make any number of swaps in order to make it a palindrome.
Return the length of the maximum length awesome substring of s.
Example 1:
Input: s = "3242415"
Output: 5
Explanation: "24241" is the longest awesome substring, we can form the palindrome "24142" with some swaps.
Example 2:
Input: s = "12345678"
Output: 1
Example 3:
Input: s = "213123"
Output: 6
Explanation: "213123" is the longest awesome substring, we can form the palindrome "231132" with some swaps.
Constraints:
1 <= s.length <= 10^5sconsists only of digits.
Solution
Approach: Prefix Parity Masks
A string can be rearranged into a palindrome exactly when at most one digit appears an odd number of times. So only the parity of each digit's count matters, and the ten parities fit in a 10-bit mask.
Let mask(i) be the parity mask of the prefix s[0..i) (bit d set when digit d appeared an odd number of times). The parities of the substring s[j..i) are mask(j) XOR mask(i). The substring is awesome when this has at most one bit set, which means:
mask(j) == mask(i): every digit appears an even number of times, ormask(j) == mask(i) XOR (1 << d)for some digitd: only digitdis odd.
For the longest substring ending at i, we want the smallest such j. So store first[m], the shortest prefix length with mask m (first[0] = 0 for the empty prefix), and for each i check the mask itself and its 10 neighbors that differ in one bit. Record first[mask(i)] only the first time a mask shows up.
Forgetting the empty prefix is the usual mistake: without first[0] = 0, a whole string like "213123" (all digits even) would not be found.
Complexity: O(10 * n) time and O(210) extra space.
class Solution:
def longestAwesome(self, s: str) -> int:
# Bit d of a mask = parity of digit d's count in a prefix.
# first[mask] = shortest prefix length with that mask (-1 if none yet)
first = [-1] * 1024
first[0] = 0
mask = 0
best = 0
for i, c in enumerate(s, 1):
mask ^= 1 << int(c)
if first[mask] == -1:
first[mask] = i
# s[j:i] is awesome when the prefix masks at j and i differ in at most one bit.
best = max(best, i - first[mask])
for d in range(10):
j = first[mask ^ (1 << d)]
if j != -1:
best = max(best, i - j)
return best