Count Substrings Rearrangeable into Palindromes
Math & Bit ManipulationAuto-graded · 22 test casesLast updated
Given a list of strings, count the number of contiguous substrings in each string whose characters can be permuted to form a valid palindrome.
Given a list of lowercase English text strings strings, analyze each string independently and compute the total number of non-empty contiguous substrings whose characters can be reordered (permuted) to form a palindrome.
A multiset of characters can be arranged into a palindrome if and only if at most one character frequency is odd.
Return a list of integers containing the count of such substrings for each string in strings, in the same order as provided in the input list.
Constraints
1 <= len(strings) <= 1000 <= len(s) <= 1000for each stringsinstrings- Each string
sconsists solely of lowercase English letters ('a'through'z').
Examples
Example 1
Input: count_palindrome_permutable_substrings(['aabb'])
Output: [9]
Example 2
Input: count_palindrome_permutable_substrings(['a', 'aa', 'abc', 'aabb'])
Output: [1, 3, 3, 9]
Hints
Hint 1
A string can be rearranged into a palindrome if and only if at most one character appears an odd number of times.
Hint 2
Think about representing the odd/even parity of character counts up to index `i` as a 26-bit integer mask.
Hint 3
How does the parity mask of substring `s[j..i-1]` relate to the prefix parity masks at index `j` and index `i`? Use a hash map to keep track of frequencies of seen prefix masks.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
To determine if a substring can be rearranged into a palindrome, we need to inspect the frequencies of its characters. A string can form a palindrome if and only if at most one character frequency is odd (all other character frequencies must be even).
Because we only care about whether character counts are even or odd, we can model character parity using bitwise operators:
- Represent the state of prefix
s[0..i-1]as a 26-bit bitmask, where bit $k$ is $1$ if the $k$-th character of the alphabet has appeared an odd number of times in the prefix, and $0$ if it has appeared an even number of times. - For any substring starting at index $j$ and ending at index $i-1$, its character count parities correspond to
mask[i] ^ mask[j]. - The substring
s[j..i-1]is rearrangeable into a palindrome ifmask[i] ^ mask[j]has either zero set bits (all character counts are even) or exactly one set bit (exactly one character count is odd).
Thus, as we iterate through each character in the string:
- We update the cumulative prefix mask
mask ^= (1 << (ord(ch) - ord('a'))). - We check how many previously seen prefix masks
mask_prevsatisfy:mask_prev == mask(0 set bits difference).mask_prev == mask ^ (1 << bit)for anybitfrom 0 to 25 (1 set bit difference).
- We add the count of such prefix masks to our total for the current string, and then update the frequency hash map with
mask.
Initializing the frequency map with {0: 1} accounts for valid substrings that start at index 0 (where the preceding prefix is empty).
Complexity
For a string of length $N$:
- Time Complexity: $O(26 \times N)$ time per string, which simplifies to $O(N)$. Across all strings in
strings, the total time complexity is $O(\sum |s|)$. - Space Complexity: $O(\min(N, 2^{26}))$ auxiliary space per string to store the unique prefix masks in the hash map.
from typing import List
def count_palindrome_permutable_substrings(strings: List[str]) -> List[int]:
answers = []
for s in strings:
counts = {0: 1} # Empty prefix mask has state 0
mask = 0
total = 0
for ch in s:
mask ^= 1 << (ord(ch) - ord('a'))
# Case 1: All character counts in substring are even
total += counts.get(mask, 0)
# Case 2: Exactly one character count in substring is odd
for bit in range(26):
total += counts.get(mask ^ (1 << bit), 0)
counts[mask] = counts.get(mask, 0) + 1
answers.append(total)
return answers