KatInterview

Count Substrings Rearrangeable into Palindromes

Math & Bit ManipulationAuto-graded · 22 test cases
HardAuto-gradedMath & Bit Manipulationbit-manipulationhash-tablestrings

Last 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) <= 100
  • 0 <= len(s) <= 1000 for each string s in strings
  • Each string s consists 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.