Palindrome Pairs (LeetCode 336): Solution and Explanation
You get a list of distinct words and must find every ordered pair of different indices (i, j) where gluing words[i] in front of words[j] produces a palindrome. Order matters, so (i, j) and (j, i) are separate answers when both work.
Watch it run step by step
Try your own input and write the code →Intuition
The obvious solution tries every ordered pair, concatenates the two words and checks the result. With n words of length up to k that is O(n² × k), which falls over once the list reaches thousands of words. To do better we need to stop pairing words blindly and instead ask, for one word, exactly which partner could possibly complete it.
Think about what a palindrome A + B looks like when A is the longer piece. The end of A must mirror B exactly, and whatever is left over in the middle of A must read the same in both directions. So if we split A into a prefix and a suffix, and the suffix is already a palindrome, then the partner B placed after A must be the reverse of the prefix. Symmetrically, if the prefix of A is a palindrome, the word placed before A must be the reverse of A's suffix.
That turns the problem into lookups. Put every word in a hash map from word to index, then for each word try all k + 1 split points. At each split, test whether the prefix or the suffix is a palindrome, reverse the other half and check the map. A word only has k + 1 splits, and each check costs O(k), so we do O(k²) work per word instead of O(n × k).
The one subtle point is double counting. Splitting at j = 0 gives an empty prefix and splitting at j = len(word) gives an empty suffix, and both would discover the same pair when two words are exact reverses. The reference code avoids that by skipping the suffix case at the last split, so each pair is reported once.
Approach: Hash map with prefix and suffix splits
- Build
wordMapfrom each word to its index so a reversed fragment can be looked up in O(k). - Loop over every word
wordat indexi, and over every split pointjfrom 0 tolen(word)inclusive. - Set
prefix = word[:j]andsuffix = word[j:]. - If
prefixis a palindrome, look upsuffix[::-1]. If it exists at a different index, that word goes in front, so append[wordMap[reversedSuffix], i]. - If
j != len(word)andsuffixis a palindrome, look upprefix[::-1]. If it exists at a different index, that word goes after, so append[i, wordMap[reversedPrefix]]. - Return the collected pairs after every word and every split has been tried.
Step-by-step example
words = ["bat", "tab", "cat"]
wordMapis {"bat": 0, "tab": 1, "cat": 2}.- Word "bat" at i = 0, split j = 0: prefix "" is a palindrome and the reversed suffix "tab" is in the map at index 1, so append [1, 0] ("tabbat").
- Splits j = 1 and j = 2 for "bat" produce palindromic pieces "b" and "t", but the reversed partners "ta" and "ab" are not words, so nothing is added. At j = 3 the prefix "bat" is not a palindrome.
- Word "tab" at i = 1, split j = 0: reversed suffix "bat" is at index 0, so append [0, 1] ("battab").
- Word "cat" never finds a partner because "tac", "ta" and "ac" are not in the map.
- The result is [[1, 0], [0, 1]].
Code: Python, Java, C++
1class Solution:
2 def palindromePairs(self, words: List[str]) -> List[List[int]]:
3 def isPalindrome(s):
4 return s == s[::-1]
5
6 wordMap = {word: i for i, word in enumerate(words)}
7 result = []
8
9 for i, word in enumerate(words):
10 for j in range(len(word) + 1):
11 prefix = word[:j]
12 suffix = word[j:]
13
14 # Case 1: prefix is palindrome, check if reversed suffix exists
15 if isPalindrome(prefix):
16 reversedSuffix = suffix[::-1]
17 if reversedSuffix in wordMap and wordMap[reversedSuffix] != i:
18 result.append([wordMap[reversedSuffix], i])
19
20 # Case 2: suffix is palindrome, check if reversed prefix exists
21 if j != len(word) and isPalindrome(suffix):
22 reversedPrefix = prefix[::-1]
23 if reversedPrefix in wordMap and wordMap[reversedPrefix] != i:
24 result.append([i, wordMap[reversedPrefix]])
25
26 return result1class Solution {
2 public List<List<Integer>> palindromePairs(String[] words) {
3 Map<String, Integer> wordMap = new HashMap<>();
4 for (int i = 0; i < words.length; i++) {
5 wordMap.put(words[i], i);
6 }
7
8 List<List<Integer>> result = new ArrayList<>();
9
10 for (int i = 0; i < words.length; i++) {
11 String word = words[i];
12 for (int j = 0; j <= word.length(); j++) {
13 String prefix = word.substring(0, j);
14 String suffix = word.substring(j);
15
16 if (isPalindrome(prefix)) {
17 String reversedSuffix = new StringBuilder(suffix).reverse().toString();
18 if (wordMap.containsKey(reversedSuffix) && wordMap.get(reversedSuffix) != i) {
19 result.add(Arrays.asList(wordMap.get(reversedSuffix), i));
20 }
21 }
22
23 if (j != word.length() && isPalindrome(suffix)) {
24 String reversedPrefix = new StringBuilder(prefix).reverse().toString();
25 if (wordMap.containsKey(reversedPrefix) && wordMap.get(reversedPrefix) != i) {
26 result.add(Arrays.asList(i, wordMap.get(reversedPrefix)));
27 }
28 }
29 }
30 }
31
32 return result;
33 }
34
35 private boolean isPalindrome(String s) {
36 int left = 0, right = s.length() - 1;
37 while (left < right) {
38 if (s.charAt(left++) != s.charAt(right--)) return false;
39 }
40 return true;
41 }
42}1class Solution {
2public:
3 vector<vector<int>> palindromePairs(vector<string>& words) {
4 unordered_map<string, int> wordMap;
5 for (int i = 0; i < words.size(); i++) {
6 wordMap[words[i]] = i;
7 }
8
9 vector<vector<int>> result;
10
11 for (int i = 0; i < words.size(); i++) {
12 string& word = words[i];
13 for (int j = 0; j <= word.size(); j++) {
14 string prefix = word.substr(0, j);
15 string suffix = word.substr(j);
16
17 if (isPalindrome(prefix)) {
18 string reversedSuffix = suffix;
19 reverse(reversedSuffix.begin(), reversedSuffix.end());
20 if (wordMap.count(reversedSuffix) && wordMap[reversedSuffix] != i) {
21 result.push_back({wordMap[reversedSuffix], i});
22 }
23 }
24
25 if (j != word.size() && isPalindrome(suffix)) {
26 string reversedPrefix = prefix;
27 reverse(reversedPrefix.begin(), reversedPrefix.end());
28 if (wordMap.count(reversedPrefix) && wordMap[reversedPrefix] != i) {
29 result.push_back({i, wordMap[reversedPrefix]});
30 }
31 }
32 }
33 }
34
35 return result;
36 }
37
38private:
39 bool isPalindrome(const string& s) {
40 int left = 0, right = s.size() - 1;
41 while (left < right) {
42 if (s[left++] != s[right--]) return false;
43 }
44 return true;
45 }
46};Time and space complexity
O(n × k²)
For each of the n words we try k + 1 split points, and at each split the palindrome checks, reversals and hash lookups each cost O(k), giving O(k²) per word.
O(n × k)
The hash map stores all n words of length up to k. The temporary slices at each split are O(k), and the output list is not counted.
Other approaches
Brute force over all pairs (time O(n² × k), space O(k))
Concatenate every ordered pair and test it directly. It is trivially correct and fine for a few hundred words, which makes it a useful checker when you test the optimized version.
Trie of reversed words (time O(n × k²), space O(n × k))
Insert every word reversed into a trie and record at each node which words have a palindromic remainder below it. Walking each word down the trie finds partners without slicing strings, which removes the hashing cost but is much longer to write.
Common mistakes
- Running the suffix case at
j = len(word)as well as the prefix case atj = 0, which reports every pair of mirror words twice. - Forgetting the
wordMap[reversedSuffix] != icheck, so a palindromic word like "aba" gets paired with itself when its own reverse is found. - Only looping
jfrom 0 tolen(word) - 1, which misses pairs involving the empty string or a full-word palindrome split. - Mixing up the output order: a reversed suffix partner goes in front of the current word, and a reversed prefix partner goes after it.
Frequently asked questions
Why is Palindrome Pairs O(n × k²) and not O(n²)?
We never compare two words directly. Each word does a fixed amount of work per split point, and there are k + 1 splits costing O(k) each, so the total depends on n linearly and on word length quadratically.
How does the empty string get handled?
If "" is in the list, any palindromic word pairs with it in both orders. The split at j = len(word) finds "" in front, and the split at j = 0 finds it after, so no special case is needed.
Is a trie faster than a hash map here?
Asymptotically they match at O(n × k²) in the usual analysis. The trie avoids building reversed substrings, which can help with long words, but the hash map version is shorter and easier to get right in an interview.