You are given an array of strings words and an integer k.
For each index i in the range [0, words.length - 1], find the length of the longest common prefix among any k strings (selected at distinct indices) from the remaining array after removing the ith element.
Return an array answer, where answer[i] is the answer for ith element.
If removing the ith element leaves the array with fewer than k strings,
answer[i] is 0.
Input: words =["jump","run","run","jump","run"], k =2Output: [3,4,4,3,4]Explanation:
* Removing index 0(`"jump"`):*`words` becomes:`["run", "run", "jump", "run"]`.`"run"` occurs 3 times. Choosing any two gives the longest common prefix `"run"`(length 3).* Removing index 1(`"run"`):*`words` becomes:`["jump", "run", "jump", "run"]`.`"jump"` occurs twice. Choosing these two gives the longest common prefix `"jump"`(length 4).* Removing index 2(`"run"`):*`words` becomes:`["jump", "run", "jump", "run"]`.`"jump"` occurs twice. Choosing these two gives the longest common prefix `"jump"`(length 4).* Removing index 3(`"jump"`):*`words` becomes:`["jump", "run", "run", "run"]`.`"run"` occurs 3 times. Choosing any two gives the longest common prefix `"run"`(length 3).* Removing index 4("run"):*`words` becomes:`["jump", "run", "run", "jump"]`.`"jump"` occurs twice. Choosing these two gives the longest common prefix `"jump"`(length 4).
To efficiently find the longest common prefix among any k strings after removing one, we can use a trie to count the number of strings sharing each prefix. By precomputing prefix and suffix tries, we can answer each query in O(L) time, where L is the string length.
classTrieNode:
def__init__(self):
self.children = {}
self.count =0classSolution:
deflongestCommonPrefixAfterRemoval(self, words: list[str], k: int) -> list[int]:
n = len(words)
pre = [TrieNode() for _ in range(n+1)]
suf = [TrieNode() for _ in range(n+1)]
definsert(root, word):
node = root
for c in word:
if c notin node.children:
node.children[c] = TrieNode()
node = node.children[c]
node.count +=1# Build prefix triesfor i in range(n):
pre[i+1] = pre[i]
insert(pre[i+1], words[i])
# Build suffix triesfor i in range(n-1, -1, -1):
suf[i] = suf[i+1]
insert(suf[i], words[i])
ans = [0] * n
for i in range(n):
node = pre[i]
node2 = suf[i+1]
l =0whileTrue:
found =Falsefor c in node.children:
if c in node2.children:
cnt = node.children[c].count + node2.children[c].count
if cnt >= k:
node = node.children[c]
node2 = node2.children[c]
l +=1 found =Truebreakifnot found:
break ans[i] = l
return ans