Longest Common Prefix of K Strings After Removal - 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 i-th element.
Return an array answer, where answer[i] is the answer for the i-th element. If removing the i-th element leaves the array with fewer than k strings, answer[i] is 0.
Input & Output
Example 1 — Basic Case
$
Input:
words = ["cat","car","card","care"], k = 2
›
Output:
[3,3,2,3]
💡 Note:
Remove "cat": best 2-combination is ["car","card"] or ["car","care"] with prefix "car" (length 3). Remove "car": best is ["card","care"] with prefix "car" (length 3). Remove "card": best is ["cat","car"] with prefix "ca" (length 2). Remove "care": best is ["car","card"] with prefix "car" (length 3).
Example 2 — Insufficient Strings
$
Input:
words = ["ab","bc"], k = 3
›
Output:
[0,0]
💡 Note:
After removing any element, only 1 string remains, but k=3 is required, so answer is [0,0].
Example 3 — No Common Prefix
$
Input:
words = ["abc","def","ghi"], k = 2
›
Output:
[0,0,0]
💡 Note:
No two strings share a common prefix, so longest common prefix length is 0 for all removals.
Constraints
- 2 ≤ words.length ≤ 100
- 1 ≤ words[i].length ≤ 100
- 1 ≤ k ≤ words.length
- words[i] consists of lowercase English letters only
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array of strings and target count k
2
Process
For each removal, find best k-combination prefix
3
Output
Array of maximum prefix lengths
Key Takeaway
🎯 Key Insight: Use trie structure to efficiently find longest common prefixes without checking all combinations
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code