HardNo. 0336

Palindrome Pairs — LeetCode 336 Python Solution

Pattern
Trie
Topics
Trie, Array, Hash Table, String
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

PythonSolution
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

Time
O(n)
Space · auxiliary
O(n)

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

Related problems
No.ProblemDifficulty
0139Word BreakMedium
0140Word Break IIHard
0648Replace WordsMedium
0692Top K Frequent WordsMedium
0720Longest Word in DictionaryMedium
0745Prefix and Suffix SearchHard

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.

Free to download. Check it runs on your machine, then pick a plan.