Problem 334
Palindrome Pairs Count
Hard · 30 pts · String, Hash Table, Trie
Problem
You are given N distinct words. Count the ordered pairs of different positions (i, j), i != j, such that the concatenation word[i] + word[j] is a palindrome. Order matters: (i, j) and (j, i) are different pairs, and each one counts if its own concatenation is a palindrome. Checking every pair directly is O(N² · L); splitting each word into a prefix and a suffix and looking up reversed words in a hash map is much faster.
Input
First line: N. Second line: the N distinct words (lowercase letters).
Output
Print the number of ordered palindrome pairs.
Constraints
1 <= N <= 5000; 1 <= word length <= 300
Example input
5 abcd dcba lls s sssll
Example output
4
Explanation
For abcd dcba lls s sssll, the palindromic concatenations are abcddcba, dcbaabcd, slls and llssssll, so there are 4 pairs.