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
Longest Common Prefix After Removal (k=2)Original:"cat""car""card""care"Remove "cat":"car""card""care"Best k=2: ["car","card"] → prefix "car" (length 3)Output:3323remove "cat"remove "car"remove "card"remove "care"
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
Asked in
Google 25 Microsoft 18 Amazon 15
18.5K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen