#3485
Longest Common Prefix of K Strings After Removal
HardArrayStringTrieHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Using a Trie allows us to efficiently store and count prefixes, making it easy to find the longest common prefix for any k strings after removing one.
⚙️
Algorithm
3 steps- 1Step 1: Build a Trie from all strings, maintaining counts of how many strings share each prefix.
- 2Step 2: For each string removed, check the counts in the Trie for the remaining strings.
- 3Step 3: Determine the maximum length of common prefixes for any k strings using the counts.
solution.py35 lines
1class TrieNode:
2 def __init__(self):
3 self.children = {}
4 self.count = 0
5
6def insert(root, word):
7 node = root
8 for char in word:
9 if char not in node.children:
10 node.children[char] = TrieNode()
11 node = node.children[char]
12 node.count += 1
13
14def longestCommonPrefix(words, k):
15 root = TrieNode()
16 for word in words:
17 insert(root, word)
18 answer = []
19 for i in range(len(words)):
20 if len(words) - 1 < k:
21 answer.append(0)
22 continue
23 max_lcp = 0
24 node = root
25 for char in words[i]:
26 if char in node.children:
27 node = node.children[char]
28 if node.count >= k:
29 max_lcp += 1
30 else:
31 break
32 else:
33 break
34 answer.append(max_lcp)
35 return answerℹ
Complexity note: Building the Trie takes O(n) time, and checking counts for each string is also O(n).
- 1Using a Trie optimizes prefix counting.
- 2Removing one string affects the counts but not the structure.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.