Skip to main content

336 - Palindrome Pairs

Details

KeyValue
Linkhttps://leetcode.com/problems/palindrome-pairs/
LanguagePython 3
Runtime3350 ms, faster than 80.91% of Python3 online submissions for Palindrome Pairs
Memory Usage26.2 MB, less than 93.16% of Python3 online submissions for Palindrome Pairs
DatastructuresDict, List[str]
AlgorithmsIteration (Divide & Conquer?)
ComplexityTime: O(N*W^2?) Memory: O(?)

Procedure

  1. ...

Code

class Solution:
def palindromePairs(self, words: List[str]) -> List[List[int]]:
result = []
d = {word[::-1]: i for i, word in enumerate(words)}

for i, word in enumerate(words):
for j in range(len(word) + 1):
prefix, suffix = word[:j], word[j:]

if prefix in d and i != d[prefix] and suffix == suffix[::-1]:
result.append([i, d[prefix]])

if suffix in d and i != d[suffix] and prefix == prefix[::-1] and j>0:
result.append([d[suffix], i])

return result