← Back to index
HardPython4 min read

Palindrome Pairs

find all pairs of words that form palindrome when concatenated by checking all prefix/suffix splits.

hash-tablestringtrie

Problem link

View on LeetCode

Solutions in this repo

  • Python../palindrome-pairs/solution.pyPython solution

for each word, try all possible splits (prefix + suffix). if prefix is palindrome, check if reverse of suffix exists in word map. if suffix is palindrome, check if reverse of prefix exists.

use hash map for O(1) word lookup. for word at index i, try splits at positions 0 to len(word). check both cases: prefix palindrome (suffix reverse in map) and suffix palindrome (prefix reverse in map).

key insight

if word1 + word2 is palindrome, either word1's prefix is palindrome (word2 reverses word1's suffix) or word1's suffix is palindrome (word2 reverses word1's prefix).

complexity

O(n * k²) time where n is words count and k is average word length. O(n) space for hash map.