Task here is to find palindromes formed by combining pairs of the original word list (so for below, stuff like "callac" and "laccal"). I thought I had an idea of pre-computing all the reversed versions of each word (N). Then for each original word, compare with each reversed word... but then we're back to N*N.
Maybe we could sort the list. And then for each word we're working on, do a binary search for words whose first character matches our word's first or last character and check from there resulting in some kind of N log N situation?
My code:
data = ["cal", "lac", "mic", "blah", "totally", "ylla", "rum", "mur", "listen", "netsil"]
def get_palindrome_pairs(words):
palindromes = []
for i in range(len(words)):
for j in range(i+1, len(words)):
combined = words[i] + words[j]
combined_swapped = words[j] + words[i]
if combined == combined[::-1]:
palindromes.append(combined)
if combined_swapped == combined_swapped[::-1]:
palindromes.append(combined_swapped)
return palindromes
print(get_palindrome_pairs(data))