Palindrome Pairs
Find every ordered pair of words whose joined text reads the same backwards, using a trie of reversed words.
Given a list of distinct words made of the lowercase letters a to z, return every pair of indices [i, j]ijwords[i] + words[j]
Example 1
Output: [[0, 1], [1, 0], [2, 4], [3, 2]]
Explanation: the joined strings are "abcddcba", "dcbaabcd", "llssssll" and "slls".
Example 2
Output: [[0, 1], [1, 0]]
Example 3
Output: [[0, 1]]
Explanation: "abccba". The longer word comes first here.
The Idea
Put two words side by side and read the result backwards. In Example 1, "lls" followed by "sssll" gives "llssssll", which reads the same both ways. So does "s" followed by "lls", which gives "slls". The order of the two words matters: "lls" followed by "s" gives "llss", and that is not a palindrome.
What makes "lls" and "sssll" fit together? The first letters of a palindrome mirror its last letters. So "lls", read forwards, has to match the end of "sssll" read backwards. Backwards, "sssll" is "llsss", and its first three letters are exactly "lls". The two letters of "sssll" that nothing mirrors, "ss" at its front, end up in the middle of the joined string. The middle has to read the same both ways on its own, and "ss" does.
Example 3 shows the same thing the other way round. There the first word, "abcc", is the longer one. Backwards, "ba" is "ab", which matches the start of "abcc". This time the letters left over belong to "abcc": its rest, "cc", has to be a palindrome, and it is.
So for each word, the question is: which other words, written backwards, start the same way as this word, or are a start of it? Checking every other word one at a time repeats a lot of work. Instead, write every word backwards and store the letters in a tree, so that words starting alike share their first links. Look at the picture below.
In the top part, every path from the root spells one word of Example 1 backwards, one letter per link. A teal dot marks where a reversed word ends, and its label names the original word, so the path l, l, s, s, s ends at the dot labelled end of "sssll". Storing words letter by letter like this, with shared starts sharing links, is called a trie.
Now walk "lls" from the root: the links l, l and s lead to the orange node. Its box says what is left: "sssll" still has "ss" unread at its front, a palindrome, so [2, 4][0, 1]
So one walk of a word through the trie compares it with every reversed word at once. Along the way, two things can happen: a reversed word ends part way through the walk, or the walk ends part way along, or right at the end of, a reversed word.
Solution Approach
Trying every pair is the simple way; the trie way needs three decisions: what each trie node keeps, how one walk finds both kinds of partner, and how to handle empty words and a word meeting itself.
Trying every pair
Why not join every two words and test the result? With n words there are n × (n − 1) ordered pairs, and each test reads the whole joined string. For 1,000 words that is 999,000 joined strings, most of them built only to be thrown away.
What each trie node keeps
What does the walk need to know at a node? Two things. First, whether some reversed word ends there, and which one: that is the teal dot in the picture. Second, which words passing through or ending at this node have a palindrome left in their unread front, like "sssll" with "ss" at the orange node.
Both are filled in while each word is stored backwards. Before following the link for a letter, check whether the letters not yet stored, the front of the word, read the same both ways. For "sssll" that is true after "ll" (front "sss"), after "lls" (front "ss") and after "llss" (front "s"). When the whole word is stored, nothing is left, and an empty front counts as a palindrome.
Finding both kinds of partner in one walk
How does one walk catch both situations? At each node, before following the next letter, check for a teal dot. If a reversed word ends there, it is shorter than the word being walked, and the pair works when the rest of the walked word is a palindrome. That is how "abcc" finds "ba".
If the walk uses up every letter, the node it stops at lists the words whose unread front is a palindrome, and each one is a partner. That is how "lls" finds "sssll". A reversed word of the same length ends right at that node, with an empty front, so it is in the list too. Because the dot check runs only before a letter is followed, a same-length partner is never counted twice. If a letter has no link, no stored word continues the walked word, and the walk stops with no pairs from that point on.
Empty words and a word meeting itself
Can a word pair with itself? The word "aba" written backwards is "aba" again, so walking "aba" ends on its own dot, and the list there holds its own index. The problem asks for two different indices, so both checks skip the walked word's own index.
An empty word "" needs no special code. Written backwards it ends at the root. When a palindrome word is walked, the root's dot is checked before its first letter, so that word followed by "" is found. Walking "" itself stops at the root at once, where the list holds every word that is a palindrome as a whole.
Java Solution
The method palindromePairs
- First, define the trie node class
. It hasNode , an array of 26 links, one per letter;next , the index of the word whose reversal ends here, or -1; andwordIndex , the list of words whose unread front is a palindrome. A helper,palindromeRest , checks whether the letters fromisPalindrome(s, lo, hi) tolo read the same both ways by moving two markers toward each other.hi - Store every word backwards with two loops, one inside the other. The outer loop takes each word
with indexw and startsi atcur . The inner loop movesroot from the last letter down to the first. Before following the link for letterj , it addsj toi whencur.palindromeRest is true, and it creates the link if it is missing.isPalindrome(w, 0, j) - After the inner loop,
is where the reversed word ends. Addcur to itsi , for the empty front, and set itspalindromeRest towordIndex .i - Walk every word forward with a second pair of loops. For each word
,w starts atcur , and the inner loop movesroot over the letters whilej is notcur . Before following letternull , if another word ends atj andcur is true, addisPalindrome(w, j, w.length() - 1) to[i, cur.wordIndex] . This is the check marked Case 1 in the code.result - If the walk fell off the trie,
iscur and the word gets no more pairs. Otherwise, addnull for every[i, b] inb other thancur.palindromeRest . This is Case 2 in the code.i - When every word has been walked, return
.result
The main
import java.util.ArrayList;
import java.util.List;
public class PalindromePairs {
private static class Node {
Node[] next = new Node[26];
int wordIndex = -1; // a reversed word ends here
List<Integer> palindromeRest = new ArrayList<>(); // unread front is a palindrome
}
public static List<List<Integer>> palindromePairs(String[] words) {
Node root = new Node();
for (int i = 0; i < words.length; i++) { // insert every word reversed
String w = words[i];
Node cur = root;
for (int j = w.length() - 1; j >= 0; j--) {
if (isPalindrome(w, 0, j)) {
cur.palindromeRest.add(i); // w[0..j] is still unread
}
int c = w.charAt(j) - 'a';
if (cur.next[c] == null) {
cur.next[c] = new Node();
}
cur = cur.next[c];
}
cur.palindromeRest.add(i); // nothing unread: empty is a palindrome
cur.wordIndex = i;
}
List<List<Integer>> result = new ArrayList<>();
for (int i = 0; i < words.length; i++) { // walk every word forward
String w = words[i];
Node cur = root;
for (int j = 0; j < w.length() && cur != null; j++) {
// Case 1: a shorter word ends here, and the rest of w is a palindrome.
if (cur.wordIndex >= 0 && cur.wordIndex != i
&& isPalindrome(w, j, w.length() - 1)) {
result.add(List.of(i, cur.wordIndex));
}
cur = cur.next[w.charAt(j) - 'a'];
}
if (cur == null) {
continue; // no reversed word continues w
}
// Case 2: all of w matched; each listed word has a palindrome left at its front.
for (int b : cur.palindromeRest) {
if (b != i) {
result.add(List.of(i, b));
}
}
}
return result;
}
private static boolean isPalindrome(String s, int lo, int hi) {
while (lo < hi) {
if (s.charAt(lo++) != s.charAt(hi--)) {
return false;
}
}
return true;
}
public static void main(String[] args) {
System.out.println(palindromePairs(new String[] {"abcd", "dcba", "lls", "s", "sssll"}));
System.out.println(palindromePairs(new String[] {"bat", "tab", "cat"}));
System.out.println(palindromePairs(new String[] {"abcc", "ba"}));
System.out.println(palindromePairs(new String[] {"a", ""}));
System.out.println(palindromePairs(new String[] {"aba"}));
System.out.println(palindromePairs(new String[] {"ab", "cd"}));
}
}
Running it prints:
[[0, 1], [1, 0], [2, 4], [3, 2]]
[[0, 1], [1, 0]]
[[0, 1]]
[[0, 1], [1, 0]]
[]
[]
Look at [3, 2][[0, 1]]
The fourth line, for ["a", ""][0, 1][1, 0]
The fifth line, for ["aba"]b != i[[0, 0]][3, 3]
Complexity
Each word is stored once and walked once, and at every letter of both passes the code may test a stretch of the word for being a palindrome.
- Time: O(n × k2) plus one step per pair reported, because each of the n words, at most k letters long, is stored once and walked once, and each letter may start an
check of up to k letters.isPalindrome - Space: O(n × k), because the trie has at most one node per stored letter, each with a fixed array of 26 links, and each word appears in at most k + 1
lists.palindromeRest
For the trie on its own, with insert and search, see