Skip to main content

Palindrome Pairs

Question

Given a list of unique words, find all pairs of distinct indices (i, j) in the given list, such that the concatenation of the two words, i.e. words[i] + words[j] is a palindrome.

Example 1
Input: ["abcd","dcba","lls","s","sssll"]

Output: [[0,1],[1,0],[3,2],[2,4]]

Solution

all//Palindrome Pairs.py


def palindrome_pairs(words):
pairs = []
for word1 in words:
for word2 in words:
if word1 != word2 and word1 + word2 == word2 + word1:
pairs.append((word1, word2))
return pairs

words = ["code", "edoc", "da", "d"]
print(palindrome_pairs(words))