Palindrome Pairs - Problem

You are given a 0-indexed array of unique strings words. A palindrome pair is a pair of integers (i, j) such that:

  • 0 <= i, j < words.length
  • i != j
  • words[i] + words[j] (the concatenation of the two strings) is a palindrome

Return an array of all the palindrome pairs of words. You must write an algorithm with O(sum of words[i].length) runtime complexity.

Input & Output

Example 1 — Multiple Palindrome Pairs
$ Input: words = ["race","car",".","ecar"]
Output: [[0,1],[1,0],[3,2]]
💡 Note: "race" + "car" = "racecar" (palindrome), "car" + "race" = "carrace" (not palindrome but "car" + "" would work with different input), "ecar" + "." = "ecar." forms palindrome logic
Example 2 — No Pairs Found
$ Input: words = ["abcd","dcba","lls","s","sssll"]
Output: [[0,1],[1,0],[3,2],[2,4]]
💡 Note: "abcd" + "dcba" = "abcddcba" (palindrome), "dcba" + "abcd" = "dcbaabcd" (palindrome), "s" + "lls" = "slls" (palindrome), "lls" + "sssll" = "llssssll" (palindrome)
Example 3 — Single Character Edge Case
$ Input: words = ["a",""]
Output: [[0,1],[1,0]]
💡 Note: "a" + "" = "a" (palindrome), "" + "a" = "a" (palindrome). Both combinations work with empty string.

Constraints

  • 1 ≤ words.length ≤ 5000
  • 0 ≤ words[i].length ≤ 300
  • words[i] consists of lowercase English letters

Visualization

Tap to expand
Palindrome Pairs: Find Concatenations That Form PalindromesInput Words:"race""car"".""ecar"index 0index 1index 2index 3"race" + "car" = "racecar" ✓"car" + "race" = "carrace" ✗"ecar" + "." = "ecar." ✓Output Pairs:[0,1][1,0][3,2]
Understanding the Visualization
1
Input
Array of unique strings: ["race", "car", ".", "ecar"]
2
Process
Find pairs where concatenation creates palindromes
3
Output
Array of index pairs: [[0,1], [1,0], [3,2]]
Key Takeaway
🎯 Key Insight: A palindrome forms when one word can complete another word's palindromic pattern
Asked in
Google 45 Amazon 38 Facebook 32 Microsoft 28
180.0K Views
Medium Frequency
~35 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen