SDE & MLE Prep

336. Palindrome Pairs

Problem

words holds distinct strings. Return every pair of indices [i, j] (i ≠ j) for which words[i] + words[j] is a palindrome.

Example: ["bat","tab","cat"] → [[0,1],[1,0]]

Constraints: up to 5000 words of length ≤ 300; aim for better than checking every pair.

Map each reversed word to its index. For every word w and every split w = pre + suf:

  • if pre is some other word reversed and suf is a palindrome → w + that word is a palindrome;
  • if suf is some other word reversed and pre is a palindrome → that word + w is a palindrome (skip the empty pre here so each pair is found once).

A trie of reversed words gives the same complexity; the hash map is simpler to write.

w = "lls" split "" + "lls"? ...  "ll" + "s": pre "ll" is a palindrome, rev(suf) = "s" is a word
    -> "s" + "lls" = "slls"  ✓

Complexity: O(n · k²) for n words of length ≤ k.

class Solution:
    def palindromePairs(self, words: List[str]) -> List[List[int]]:
        rev = {w[::-1]: i for i, w in enumerate(words)}
        res = []
        for i, w in enumerate(words):
            for j in range(len(w) + 1):
                pre, suf = w[:j], w[j:]
                if pre in rev and rev[pre] != i and suf == suf[::-1]:
                    res.append([i, rev[pre]])
                if j and suf in rev and rev[suf] != i and pre == pre[::-1]:
                    res.append([rev[suf], i])
        return res