Coding Interview PatternsPalindrome Pairs
HardTrie
Palindrome Pairs
Explanation & Solution
Description
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.lengthi != jwords[i] + words[j](the concatenation) is a palindrome
Return an array of all the palindrome pairs [i, j], sorted in ascending order.
Input:words = ["abcd","dcba","lls","s","sssll"]
0
abcd
1
dcba
2
lls
3
s
4
sssll
Output: [[0,1],[1,0],[2,4],[3,2]]
Explanation:
words[0] + words[1]="abcddcba"which is a palindrome.words[1] + words[0]="dcbaabcd"which is a palindrome.words[2] + words[4]="llssssll"which is a palindrome.words[3] + words[2]="slls"which is a palindrome.
Constraints
1 <= words.length <= 50000 <= words[i].length <= 300words[i]consists of lowercase English letters- All strings in
wordsare unique
Approach
Trie pattern
1. Build a Reversed-Word Trie
- Insert each word reversed into a trie
- At each node during insertion, if the remaining prefix of the reversed word (i.e., the uninserted portion) is a palindrome, record the word's index in a
palindromeSuffixeslist at that node - At the end of each word insertion, mark the
wordIndexand also add the index topalindromeSuffixes
2. Search for Palindrome Pairs
- For each word, traverse the trie character by character:
- Case 1: If we hit a node with a
wordIndex(a complete reversed word ends here) and the remaining suffix of the current word is a palindrome, then concatenatingwords[i] + words[wordIndex]forms a palindrome - Case 2: After fully traversing the current word in the trie, all indices in the current node's
palindromeSuffixeslist can form a palindrome pair with the current word
3. Palindrome Check Helper
- A helper function checks if a substring is a palindrome using the two-pointer technique
- This is called during both trie building and searching
4. Sort and Return
- Collect all valid
[i, j]pairs into a results array - Sort the results in ascending order and return
Key Insight
- Inserting reversed words into the trie allows us to find pairs where one word is the reverse of a prefix/suffix of another
- The
palindromeSuffixeslist captures cases where the leftover portion is itself a palindrome
Time
O(n * k^2) where n is the number of words and k is the average word length