Count Pairs That Can Be Rearranged Into a Palindrome
You are given an array s of N strings. Each string contains only lowercase English letters.
A pair of indices (i, j) is called a valid palindrome pair if:
- 0 <= i < j < N, and
- after concatenating s[i] + s[j], there exists at least one permutation of the resulting string that is a palindrome.
Return the number of valid palindrome pairs in the array.
Notes:
- You are not required to check whether s[i] + s[j] itself is a palindrome.
- You only need to check whether some rearrangement of the concatenated string can form a palindrome.
- Two pairs are different if their indices are different.
- The pair (i, j) is considered the same as (j, i), so count each unordered pair only once.
- A string can be rearranged into a palindrome if at most one character has an odd frequency.
Example 1:
Input: s = ["ab", "b", "aa", "c"]
Output: 3
Explanation:
The valid pairs are:
- (0, 1) → "ab" + "b" = "abb" → can be rearranged into "bab"
- (1, 2) → "b" + "aa" = "baa" → can be rearranged into "aba"
- (2, 3) → "aa" + "c" = "aac" → can be rearranged into "aca"
So, the answer is 3.
Example 2:
Input: s = ["abc", "cba", "d", "dd", "abcd"]
Output: 4
Explanation:
The valid pairs are:
- (0, 1) → "abccba"
- (0, 4) → "abcabcd"
- (1, 4) → "cbaabcd"
- (2, 3) → "ddd"
Each of these concatenated strings can be rearranged into a palindrome.
Now Your Turn!
Pick the correct output for the given inputInput: s = ["a", "ab", "b", "cc"]
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 1 <= N <= 100000
- Each string consists only of lowercase English letters from 'a' to 'z'
- The total number of characters across all strings is less than 1000000