You are given a 0-indexed array of unique strings words.
A palindrome pair is a pair of integers (i, j) such that:
0 <= i, j < words.length,
i != j, and
words + words[j] (the concatenation of the two strings) is a palindrome
Return an array of all the palindrome pairs of words.
You must write an algorithm with O(sum of words.length) runtime complexity.
Example 1:
Input: words = [“abcd”,“dcba”,“lls”,“s”,“sssll”] Output: [[0,1],[1,0],[3,2],[2,4]] Explanation: The palindromes are [“abcddcba”,“dcbaabcd”,“slls”,“llssssll”]
Example 2:
Input: words = [“bat”,“tab”,“cat”] Output: [[0,1],[1,0]] Explanation: The palindromes are [“battab”,“tabbat”]
Example 3:
Input: words = [“a”,“”] Output: [[0,1],[1,0]] Explanation: The palindromes are [“a”,“a”]
Constraints:
The main idea is to use a hash map (or hash table) to store the reversed versions of each word. This allows us to quickly check if there is a word in the array that, when concatenated with another word, forms a palindrome.
2. Palindrome Checks:
For each word, the code checks if any prefix or suffix forms a palindrome. If a suffix is a palindrome, it checks if the reverse of the prefix exists in the hash map. If a prefix is a palindrome, it checks if the reverse of the suffix exists in the hash map.
By checking both the prefix and suffix, the code can detect potential palindrome pairs that can be formed by concatenating two different words in different orders.
3. Efficient String Handling:
The code carefully manages memory, ensuring that strings are duplicated when stored in the hash map. This avoids issues with accessing freed memory, which was a problem in earlier versions of the code.
4. Use of a Hash Map:
The hash map is used to store the reversed words along with their indices. This allows for O(1) average-time complexity lookups, which is crucial for achieving the required efficiency given the constraints.