#3093
Longest Common Suffix Queries
HardArrayStringTrieTrieString Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n + m) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n + m)Space O(n)
By reversing the strings, we can transform the problem into finding the longest common prefix. This allows us to use a Trie data structure to efficiently store and retrieve the best matches based on our criteria.
⚙️
Algorithm
4 steps- 1Step 1: Reverse all strings in wordsContainer and insert them into a Trie, storing the index of the string at each node.
- 2Step 2: For each word in wordsQuery, reverse it and traverse the Trie to find the longest common prefix.
- 3Step 3: During traversal, keep track of the best index based on the criteria (longest prefix, smallest length, earliest occurrence).
- 4Step 4: Store the best index for each query in the result array.
solution.py38 lines
1class TrieNode:
2 def __init__(self):
3 self.children = {}
4 self.index = -1
5
6class Trie:
7 def __init__(self):
8 self.root = TrieNode()
9
10 def insert(self, word, index):
11 node = self.root
12 for char in word:
13 if char not in node.children:
14 node.children[char] = TrieNode()
15 node = node.children[char]
16 node.index = index
17
18 def search_best(self, word):
19 node = self.root
20 best_index = -1
21 for char in word:
22 if char in node.children:
23 node = node.children[char]
24 best_index = node.index
25 else:
26 break
27 return best_index
28
29def longestCommonSuffix(wordsContainer, wordsQuery):
30 trie = Trie()
31 for index, word in enumerate(wordsContainer):
32 trie.insert(word[::-1], index)
33
34 ans = []
35 for query in wordsQuery:
36 best_index = trie.search_best(query[::-1])
37 ans.append(best_index)
38 return ansℹ
Complexity note: The complexity is linear because we only traverse each string once for insertion into the Trie and once for searching, making it efficient.
- 1Reversing strings simplifies the problem to finding prefixes.
- 2Using a Trie allows for efficient storage and retrieval based on common characters.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.