Longest Common Prefix of K Strings After Removal Problem
Description
LeetCode Problem 3485.
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 i^th element.
Return an array answer, where answer[i] is the answer for i^th element. If removing the i^th element leaves the array with fewer than k strings, answer[i] is 0.
Example 1:
Input: words = ["jump","run","run","jump","run"], k = 2
Output: [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).
Example 2:
Input: words = ["dog","racer","car"], k = 2
Output: [0,0,0]
Explanation:
- Removing any index results in an answer of 0.
Constraints:
1 <= k <= words.length <= 10^51 <= words[i].length <= 10^4words[i]consists of lowercase English letters.- The sum of
words[i].lengthis smaller than or equal10^5.
Solution
Approach: Trie and a Segment Tree over Depths
Insert all words into a trie, storing in every node how many words pass through it. A node with count at least k means k words share the prefix that ends there, so the answer without any removal is the largest depth among such nodes.
Removing word i lowers the count by one along its own path only. A node on that path stops being usable exactly when its count was k; call these the fragile nodes of word i. Nodes with a count above k stay usable, and nodes off the path are untouched.
Let cnt[d] be the number of nodes at depth d whose count is at least k. Keep a segment tree over depths that stores the largest depth with cnt[d] > 0. For each word:
- For each of its fragile nodes, decrease
cntat that depth by one and update the tree. - Read the largest depth at the root of the tree. That is the answer for this word.
- Undo the changes.
If n - 1 < k, every answer is 0.
Complexity: O(S + F log S) time and O(S) space, where S is the total length of all words and F is the total number of fragile nodes (at most S).
class Solution:
def longestCommonPrefix(self, words: List[str], k: int) -> List[int]:
n = len(words)
ans = [0] * n
if n - 1 < k:
return ans
trie = [{'count': 0, 'depth': 0, 'children': [-1] * 26}]
for word in words:
cur = 0
for c in word:
idx = ord(c) - 97
if trie[cur]['children'][idx] == -1:
trie[cur]['children'][idx] = len(trie)
trie.append(
{
'count': 0,
'depth': trie[cur]['depth'] + 1,
'children': [-1] * 26,
}
)
cur = trie[cur]['children'][idx]
trie[cur]['count'] += 1
max_depth = 0
for i in range(1, len(trie)):
if trie[i]['count'] >= k:
max_depth = max(max_depth, trie[i]['depth'])
global_count = [0] * (max_depth + 1)
for i in range(1, len(trie)):
node = trie[i]
if node['count'] >= k and node['depth'] <= max_depth:
global_count[node['depth']] += 1
fragile_list = [[] for _ in range(n)]
for i, word in enumerate(words):
cur = 0
for c in word:
idx = ord(c) - 97
cur = trie[cur]['children'][idx]
if trie[cur]['count'] == k:
fragile_list[i].append(trie[cur]['depth'])
seg_size = max_depth
if seg_size < 1:
return ans
tree = [-1] * (4 * (seg_size + 1))
def build(idx: int, l: int, r: int) -> None:
if l == r:
tree[idx] = l if global_count[l] > 0 else -1
return
mid = (l + r) // 2
build(idx * 2, l, mid)
build(idx * 2 + 1, mid + 1, r)
tree[idx] = max(tree[idx * 2], tree[idx * 2 + 1])
def update(idx: int, l: int, r: int, pos: int, new_val: int) -> None:
if l == r:
tree[idx] = l if new_val > 0 else -1
return
mid = (l + r) // 2
if pos <= mid:
update(idx * 2, l, mid, pos, new_val)
else:
update(idx * 2 + 1, mid + 1, r, pos, new_val)
tree[idx] = max(tree[idx * 2], tree[idx * 2 + 1])
build(1, 1, seg_size)
for i in range(n):
for d in fragile_list[i]:
update(1, 1, seg_size, d, global_count[d] - 1)
res = tree[1]
ans[i] = 0 if res == -1 else res
for d in fragile_list[i]:
update(1, 1, seg_size, d, global_count[d])
return ans