Tutorialspoint
Problem
Solution
Submissions

Palindrome Pairs

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

Write a C program to find all pairs of unique indices (i, j) such that the concatenation of words[i] + words[j] forms a palindrome. Given a list of unique words, you need to return all the pairs of indices where concatenating the words at those indices results in a palindrome string.

Example 1
  • Input: words = ["lls", "s", "sssll"]
  • Output: [[0,1], [1,0], [2,1]]
  • Explanation:
     Step 1: Check all possible pairs for palindrome concatenation
     Step 2: words[0] + words[1] = "lls" + "s" = "llss" (not palindrome)
     Step 3: words[1] + words[0] = "s" + "lls" = "slls" (not palindrome)
     Step 4: words[0] + words[1] = "lls" + "s" = "llss", words[1] + words[0] = "s" + "lls" = "slls", words[2] + words[1] = "sssll" + "s" = "ssslls" (palindrome)
Example 2
  • Input: words = ["abcd", "dcba", "lls", "s", "sssll"]
  • Output: [[0,1], [1,0], [3,2], [2,4]]
  • Explanation:
     Step 1: "abcd" + "dcba" = "abcddcba" (palindrome)
     Step 2: "dcba" + "abcd" = "dcbaabcd" (palindrome)
     Step 3: "s" + "lls" = "slls" (not palindrome), but reverse combinations work
     Step 4: Multiple valid palindrome pairs found
Constraints
  • 1 <= words.length <= 5000
  • 0 <= words[i].length <= 300
  • words[i] consists of lowercase English letters
  • All words are unique
  • Time Complexity: O(n^2 * m) where n is number of words, m is average length
  • Space Complexity: O(1) excluding output array
ArraysStringsFacebookAirbnb
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

  • Check every pair of words (i, j) where i != j
  • For each pair, concatenate words[i] + words[j] and check if it's a palindrome
  • Use a helper function to verify if a string is a palindrome
  • Store valid pairs as [i, j] indices in the result array
  • Iterate through all combinations systematically to avoid missing pairs
  • Handle edge cases like empty strings appropriately

Steps to solve by this approach:

 Step 1: Create a helper function to check if a given string is a palindrome using two pointers
 Step 2: Initialize result array and counter to store palindrome pairs
 Step 3: Use nested loops to check all possible pairs (i, j) where i != j
 Step 4: For each pair, concatenate words[i] + words[j] to form a new string
 Step 5: Use the palindrome helper function to check if concatenated string is palindrome
 Step 6: If palindrome is found, store the indices [i, j] in result array
 Step 7: Return all found palindrome pairs with their respective indices

Submitted Code :