Palindrome Pairs — LeetCode 336 Python Solution

HardTrieArrayHash TableString
Problem
#336
Pattern
Trie
Reading time
2 min

The problem

You are given a 0-indexed array of unique strings words. A palindrome pair is a pair of integers (i, j) such that: 0 <= i, j < words.length, i != j, and words[i] + words[j] (the concatenation of the two strings) is a palindrome.

Example

Input
words = ["abcd","dcba","lls","s","sssll"]
Output
[[0,1],[1,0],[3,2],[2,4]]
Explanation
The palindromes are ["abcddcba","dcbaabcd","slls","llssssll"]

Python solution

Python
class Solution:
    def palindromePairs(self, words: List[str]) -> List[List[int]]:
        d = {w: i for i, w in enumerate(words)}
        ans = []
        for i, w in enumerate(words):
            for j in range(len(w) + 1):
                a, b = w[:j], w[j:]
                ra, rb = a[::-1], b[::-1]
                if ra in d and d[ra] != i and b == rb:
                    ans.append([i, d[ra]])
                if j and rb in d and d[rb] != i and a == ra:
                    ans.append([d[rb], i])
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Trie

Store a set of words by their shared prefixes so lookups cost the length of the word. LeetCode 336. Palindrome Pairs is filed here because LeetCode tags it Trie, which is the vocabulary this hub collects.

The trie guide has the Python template for the pattern and the 49 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 336. Palindrome Pairs?
LeetCode 336. Palindrome Pairs is rated Hard on LeetCode.
What is the time complexity of LeetCode 336. Palindrome Pairs?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 336. Palindrome Pairs?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 336. Palindrome Pairs cover?
LeetCode 336. Palindrome Pairs is tagged Trie, Array, Hash Table and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview