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"]
Output: [[0,1]]
💡 Note: "race" + "car" = "racecar" which is a palindrome. So pair (0,1) is valid.
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 - Hash Map Approach INPUT words array (0-indexed) [0] "race" [1] "car" [2] "." [3] "ecar" Build Hash Map (word --> index) "race" --> 0 "car" --> 1 "." --> 2 "ecar" --> 3 rev: "ecar" rev: "rac" rev: "." rev: "race" O(n) hash map lookup for fast reverse search ALGORITHM STEPS 1 Build Hash Map Store word --> index pairs 2 Check Prefix/Suffix Split word at each position 3 Find Reverse Match Lookup reversed prefix/suffix 4 Verify Palindrome Check remaining is palindrome Example: "race" + "car" "race" reversed = "ecar" "car" reversed = "rac" Check: "racecar" palindrome? OK - YES! Check: "carrace" palindrome? OK - YES! FINAL RESULT Valid Palindrome Pairs Found: [0, 1] "race" + "car" = "racecar" [1, 0] "car" + "race" = "carrace" [3, 2] "ecar" + "." = "ecar." OUTPUT: [[0,1],[1,0],[3,2]] Time Complexity: O(sum of words[i].length) Key Insight: For each word, split into prefix and suffix at every position. If the prefix is a palindrome and the reversed suffix exists in the hash map, we found a valid pair. Same logic applies for suffix being palindrome and reversed prefix lookup. This avoids O(n^2) pairwise comparison. TutorialsPoint - Palindrome Pairs | Hash Map with Prefix/Suffix Analysis
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