Palindrome Pairs
Master this topic with zero to advance depth.
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
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.
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.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.