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], with i and j different, such that words[i] + words[j] is a palindrome. A palindrome reads the same from left to right as from right to left, like "slls". The pairs can be returned in any order.

Example 1
Input: words = ["abcd", "dcba", "lls", "s", "sssll"]
Output: [[0, 1], [1, 0], [2, 4], [3, 2]]
Explanation: the joined strings are "abcddcba", "dcbaabcd", "llssssll" and "slls".
Example 2
Input: words = ["bat", "tab", "cat"]
Output: [[0, 1], [1, 0]]
Example 3
Input: words = ["abcc", "ba"]
Output: [[0, 1]]
Explanation: "abccba". The longer word comes first here.
Solution

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.

Two tries of reversed words. In Example 1, walking lls from the root follows the links l, l, s on the path of sssll reversed and stops at the orange node, where sssll still has ss unread at its front, a palindrome, giving the pair [2, 4]. In Example 3, walking abcc passes the end of ba after a, b, and the rest of abcc, cc, is a palindrome, giving [0, 1].

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] is a pair. In the lower part, walking "abcc" passes the dot labelled end of "ba" after a and b. The rest of "abcc", "cc", is a palindrome, so [0, 1] is a pair.

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 works in these steps:

  1. First, define the trie node class Node. It has next, an array of 26 links, one per letter; wordIndex, the index of the word whose reversal ends here, or -1; and palindromeRest, the list of words whose unread front is a palindrome. A helper, isPalindrome(s, lo, hi), checks whether the letters from lo to hi read the same both ways by moving two markers toward each other.
  2. Store every word backwards with two loops, one inside the other. The outer loop takes each word w with index i and starts cur at root. The inner loop moves j from the last letter down to the first. Before following the link for letter j, it adds i to cur.palindromeRest when isPalindrome(w, 0, j) is true, and it creates the link if it is missing.
  3. After the inner loop, cur is where the reversed word ends. Add i to its palindromeRest, for the empty front, and set its wordIndex to i.
  4. Walk every word forward with a second pair of loops. For each word w, cur starts at root, and the inner loop moves j over the letters while cur is not null. Before following letter j, if another word ends at cur and isPalindrome(w, j, w.length() - 1) is true, add [i, cur.wordIndex] to result. This is the check marked Case 1 in the code.
  5. If the walk fell off the trie, cur is null and the word gets no more pairs. Otherwise, add [i, b] for every b in cur.palindromeRest other than i. This is Case 2 in the code.
  6. When every word has been walked, return result.

The main method runs the three examples, a palindrome next to an empty word, a single palindrome word, and two words that share no letters.

Java
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:

Output
[[0, 1], [1, 0], [2, 4], [3, 2]]
[[0, 1], [1, 0]]
[[0, 1]]
[[0, 1], [1, 0]]
[]
[]

Look at [3, 2] at the end of the first line. Walking "s" stops on the dot labelled end of "s", and storing "lls" backwards put index 2 in that node's list, because the unread front "ll" is a palindrome. All four pairs of Example 1 come from the list check; [[0, 1]] on the third line comes from the dot check, as "abcc" passes the end of "ba".

The fourth line, for ["a", ""], has both orders. Walking "a" meets the empty word's dot at the root, which gives [0, 1]. Walking "" stops at the root, where the list holds "a", which gives [1, 0].

The fifth line, for ["aba"], is empty because of the check b != i. With that check removed, the same input prints [[0, 0]], and Example 1 also gains [3, 3], "s" joined with itself. The last line is empty because the root has no link for "a" or "c", so both walks stop before their first letter.

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 isPalindrome check of up to k letters.
  • 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 palindromeRest lists.

For the trie on its own, with insert and search, see Implement Trie.