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
preis some other word reversed andsufis a palindrome →w + that wordis a palindrome; - if
sufis some other word reversed andpreis a palindrome →that word + wis a palindrome (skip the emptyprehere 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
assert sorted(Solution().palindromePairs(["abcd", "dcba", "lls", "s", "sssll"])) == [[0, 1], [1, 0], [2, 4], [3, 2]]
assert sorted(Solution().palindromePairs(["bat", "tab", "cat"])) == [[0, 1], [1, 0]]
assert sorted(Solution().palindromePairs(["a", ""])) == [[0, 1], [1, 0]]
assert sorted(Solution().palindromePairs(["a", "b", "c"])) == []
assert sorted(Solution().palindromePairs(["ab", "ba", "aba"])) == [[0, 1], [0, 2], [1, 0], [2, 1]] # "ababa" twice
class Solution {
public List<List<Integer>> palindromePairs(String[] words) {
Map<String, Integer> rev = new HashMap<>();
for (int i = 0; i < words.length; i++) rev.put(new StringBuilder(words[i]).reverse().toString(), i);
List<List<Integer>> res = new ArrayList<>();
for (int i = 0; i < words.length; i++) {
String w = words[i];
for (int j = 0; j <= w.length(); j++) {
String pre = w.substring(0, j), suf = w.substring(j);
Integer k = rev.get(pre);
if (k != null && k != i && isPal(suf)) res.add(List.of(i, k));
k = rev.get(suf);
if (j > 0 && k != null && k != i && isPal(pre)) res.add(List.of(k, i));
}
}
return res;
}
private boolean isPal(String s) {
for (int i = 0, j = s.length() - 1; i < j; i++, j--) if (s.charAt(i) != s.charAt(j)) return false;
return true;
}
}
func palindromePairs(words []string) [][]int {
isPal := func(s string) bool {
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
if s[i] != s[j] {
return false
}
}
return true
}
reverse := func(s string) string {
b := []byte(s)
for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
b[i], b[j] = b[j], b[i]
}
return string(b)
}
rev := map[string]int{}
for i, w := range words {
rev[reverse(w)] = i
}
res := [][]int{}
for i, w := range words {
for j := 0; j <= len(w); j++ {
pre, suf := w[:j], w[j:]
// w + words[k] is a palindrome if words[k] reversed == pre and suf is a palindrome
if k, ok := rev[pre]; ok && k != i && isPal(suf) {
res = append(res, []int{i, k})
}
// words[k] + w is a palindrome if words[k] reversed == suf and pre is a palindrome
if k, ok := rev[suf]; ok && j > 0 && k != i && isPal(pre) {
res = append(res, []int{k, i})
}
}
}
return res
}