Problem
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.
Examples
Example 1
|
|
Example 2
|
|
Constraints
1 <= k <= words.length <= 10^5
1 <= words[i].length <= 10^4
words[i]
consists of lowercase English letters.- The sum of
words[i].length
is smaller than or equal105
.
Solution
Method 1 – Trie with Dynamic Frequency Tracking
Intuition
The key insight is to use a modified Trie data structure where each node tracks the frequency of words passing through it. We can efficiently determine the longest common prefix among k strings by maintaining a global frequency map and a sorted set of valid prefix lengths.
The strategy involves initially building a complete Trie with all words, then for each word removal, temporarily removing it from the Trie, checking the maximum valid prefix length, and reinserting it back.
Approach
-
Enhanced Trie Structure: Create a Trie where each node contains a frequency counter representing how many words pass through that node.
-
Global Tracking: Maintain a frequency map that counts how many prefix lengths have frequency ≥ k, and a descending-ordered set to quickly access the maximum valid prefix length.
-
Initial Population: Insert all words into the Trie. During insertion, when a node’s frequency reaches k, increment the count for that prefix length in the global map and add it to the sorted set.
-
Simulation Process: For each word to be “removed”:
- Temporarily erase the word from the Trie
- When a node’s frequency drops below k, decrement the corresponding length count in the map
- If a length count reaches zero, remove it from the sorted set
- Record the maximum valid prefix length (largest element in the set)
- Reinsert the word back into the Trie
-
Result Extraction: The maximum element in the sorted set gives the answer for each removal scenario.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n × L)
, where n is the number of words and L is the average word length. Each word is inserted and removed from the Trie twice, and each operation takes O(L) time. - 🧺 Space complexity:
O(n × L)
, for storing the Trie structure with all unique prefixes and the additional data structures for frequency tracking.