Tutorialspoint
Problem
Solution
Submissions

Palindrome Pairs

Certification: Advanced Level Accuracy: 33.33% Submissions: 3 Points: 15

Write a Java program to find all pairs of distinct indices i and j in the given list of words where the concatenation of the two words, i.e., words[i] + words[j] is a palindrome.

Example 1
  • Input: words = ["abcd", "dcba", "lls", "s", "sssll"]
  • Output: [[0, 1], [1, 0], [3, 2], [2, 4]]
  • Explanation: Step 1: words[0] + words[1] = "abcd" + "dcba" = "abcddcba" is a palindrome. Step 2: words[1] + words[0] = "dcba" + "abcd" = "dcbaabcd" is a palindrome. Step 3: words[3] + words[2] = "s" + "lls" = "slls" is a palindrome. Step 4: words[2] + words[4] = "lls" + "sssll" = "llssssll" is a palindrome.
Example 2
  • Input: words = ["bat", "tab", "cat"]
  • Output: [[0, 1], [1, 0]]
  • Explanation: Step 1: words[0] + words[1] = "bat" + "tab" = "battab" is a palindrome. Step 2: words[1] + words[0] = "tab" + "bat" = "tabbat" is a palindrome. Step 3: words[0] + words[2] = "bat" + "cat" = "batcat" is not a palindrome. Step 4: words[2] + words[0] = "cat" + "bat" = "catbat" is not a palindrome.
Constraints
  • 1 <= words.length <= 5000
  • 0 <= words[i].length <= 300
  • words[i] consists of lowercase English letters.
  • All entries in words are distinct.
  • Time Complexity: O(n * k²) where n is the number of words and k is the average length of words
  • Space Complexity: O(n * k)
Linked ListTrie PwCSnowflake
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a trie data structure to efficiently search for palindrome pairs.
  • For each word, check if its reverse exists in the list.
  • Handle empty strings as special cases.
  • Consider partial matches where only part of the word needs to be palindromic.
  • Preprocess the list to efficiently look up words.

Steps to solve by this approach:

 Step 1: Create a hashmap to store each word and its index for quick lookup.

 Step 2: For each word, check if the reversed version exists in the map.
 Step 3: Handle the empty string as a special case. If empty string exists and current word is a palindrome, they form palindrome pairs.
 Step 4: For each word, split it into prefix and suffix at every position.
 Step 5: If the prefix is a palindrome, check if the reversed suffix exists in the map.
 Step 6: If the suffix is a palindrome, check if the reversed prefix exists in the map.
 Step 7: Collect all valid pairs of indices where concatenating the words forms a palindrome.

Submitted Code :