Palindrome Pairs
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Trie.
Palindrome Pairs
Given a list of unique words, return all pairs of distinct indices
(i, j) such that the concatenation of the two words words[i] + words[j] is a palindrome.Visual Representation
Words: ["abcd", "dcba", "lls", "s", "sssll"]
Pairs:
1. "abcd" + "dcba" = "abcddcba" (Palindrome)
2. "dcba" + "abcd" = "dcbaabcd" (Palindrome)
3. "s" + "lls" = "slls" (Palindrome)
4. "sssll" + "lls" = "ssslllls" (Wait, no...)
Wait: "lls" + "s" = "llss" (No)
Actual: "sssll" + "lls" -> "ssslllls" NO.
Let's check "lls" reverse is "sll".
If we pick i="sssll", j="lls", words[i]+words[j] = "ssslllls" Fails.
Correct for "lls": s + lls = slls (Correct).Examples
Input: words = ["abcd","dcba","lls","s","sssll"]
Output: [[0,1],[1,0],[3,2],[2,4]]
Approach 1
Level I: Brute Force (Check all pairs)
Intuition
Iterate through every pair of indices in the array. Construct the string
words[i] + words[j] and check if it is a palindrome. This is , which is too slow for large inputs.⏱ O(N^2 * L)💾 O(1)
Approach 2
Level III: Trie (Suffix-to-Prefix matching)
Intuition
For a word , we want to find such that is a palindrome. This happens if can be split into where is a palindrome and is the reverse of , OR if where is a palindrome and is the reverse of . A Trie storing words in reverse allows us to efficiently find these matches.
⏱ O(N * L^2).💾 O(N * L).
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.