336. Palindrome Pairs
Given a list ofuniquewords, find all pairs ofdistinctindices(i, j)
in the given list, so that the concatenation of the two words, i.e.words[i] + words[j]
is a palindrome.
Example 1:
Example 2:
Thoughts:
Build the trie tree in a reverse order ( assume the answer will be "word" + "reverse suffix" in the trie tree). For each node N that consists of:
the corresponding word index for current trie tree sequence representation from the root.
next: children nodes
cover list (list of word index in which the word contains the current trie suffix and MAY also contain palindrome on its left part itself.
Search each word w1 matching suffix by traversing down the trie tree. If there is a stop node before the leaf node of the Trie tree (TrieNode that represents a word w2 in reverse order and that word is not the wording being searched itself (w2 != w1)) and also the rest part of w1 (len(l2) > len(w1)) is also a palindrome, then an concatenation of w1 + w2 is an answer. Else if at the leaf node of the Trie, then adding in every index element in terminal nodes' cover list such that the concatenation of w2 + w1 are also answers. Thus, we find all the solutions.
Code: T: O(max(n * k^2, n^2) S:O(n^2 * k)
Last updated
Was this helpful?