1242. Palindrome-Ready Word Pairs

A word-game app wants to pair up words whose letters can be shuffled into a palindrome. You are given an array words of lowercase words. For an index pair i < j, the pair is palindrome-ready when all the letters of words[i] followed by all the letters of words[j] can be rearranged into a palindrome, which happens exactly when at most one letter occurs an odd number of times in the combined text.

Return, as a long, the number of palindrome-ready pairs (i, j) with i < j. Equal words at different indices form distinct pairs, and a word may take part in many pairs. Reduce each word to a 26-bit letter-parity mask, then count pairs with hash-map lookups. The intended solution runs in O(26 * n) time and O(n) space, where n is the length of words.

Example 1

Input:
words = ["plover","relpov","knoll","lok","nn","zephyr","hyper","kayak"]
Output:
3
Explanation:

Only plover with relpov, nn with kayak, and zephyr with hyper leave at most one letter with an odd count, so 3 pairs work.

Example 2

Input:
words = ["quiz","jazz","fizz","mink","kimn","zip","pizza"]
Output:
1
Explanation:

Only mink and kimn together have all letters even, and every other pairing leaves at least two odd letters, giving 1.

Example 3

Input:
words = ["wombat","batwom","tomb","bot","gnu","ugn"]
Output:
3
Explanation:

Wombat with batwom, tomb with bot, and gnu with ugn each leave at most one odd letter, giving 3 pairs.

Constraints

  • 1 ≤ words.length ≤ 105

  • 1 ≤ words[i].length ≤ 10

  • words[i] consists of lowercase English letters

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 6,000 msC++ 1,500 msJava 3,000 msJavaScript 3,000 msTypeScript 3,000 ms

Expected complexity

Time
O(26n)
Space
O(n)

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…