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.length
  • i != j
  • words[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 <= 5000
  • 0 <= words[i].length <= 300
  • words[i] consists of lowercase English letters
  • All strings in words are 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 palindromeSuffixes list at that node
  • At the end of each word insertion, mark the wordIndex and also add the index to palindromeSuffixes

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 concatenating words[i] + words[wordIndex] forms a palindrome
  • Case 2: After fully traversing the current word in the trie, all indices in the current node's palindromeSuffixes list 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 palindromeSuffixes list 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

Solution Code