Tutorialspoint
Problem
Solution
Submissions

Palindrome Pairs

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 15

Write a C++ program to find all pairs of distinct indices i and j in an array of words such that the concatenation of words[i] + words[j] forms a palindrome.

Example 1
  • Input: words = ["bat", "tab", "cat"]
  • Output: [[0,1], [1,0]]
  • Explanation:
    • The palindrome pairs are:
    • - "bat" + "tab" = "battab", which is a palindrome
    • - "tab" + "bat" = "tabbat", which is a palindrome
Example 2
  • Input: words = ["abcd", "dcba", "lls", "s", "sssll"]
  • Output: [[0,1], [1,0], [2,4], [3,2]]
  • Explanation:
    • The palindrome pairs are:
    • - "abcd" + "dcba" = "abcddcba", which is a palindrome
    • - "dcba" + "abcd" = "dcbaabcd", which is a palindrome
    • - "lls" + "sssll" = "llssssll", which is a palindrome
    • - "s" + "lls" = "slls", which is a palindrome
Constraints
  • 1 ≤ words.length ≤ 5000
  • 0 ≤ words[i].length ≤ 300
  • words[i] consists of lowercase English letters
  • Time Complexity: O(n * k²) where n is the number of words and k is the maximum length of a word
  • Space Complexity: O(n * k)
Hash MapIBMPwC
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 hash map to store words and their indices for quick lookup
  • For each word, check if its reverse exists in the array
  • Also check if any prefix or suffix of the word forms a palindrome
  • Be careful to exclude the word from pairing with itself
  • Pay attention to empty strings, which can form palindromes with any palindromic word

Steps to solve by this approach:

 Step 1: Create a hash map to store each word and its index for quick lookup.
 Step 2: For each word, check if its reverse exists in the array to form a palindrome.
 Step 3: Handle the special case of an empty string, which can form a palindrome with any palindromic word.
 Step 4: For each word, check all its prefixes. If a prefix is a palindrome, check if the reversed suffix exists in the array.
 Step 5: Similarly, check all suffixes. If a suffix is a palindrome, check if the reversed prefix exists in the array.
 Step 6: Avoid adding duplicates and pairing a word with itself.
 Step 7: Return all valid palindrome pairs found.

Submitted Code :