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 of K Strings After Removal INPUT words[] array: "cat" i=0 "car" i=1 "card" i=2 "care" i=3 k = 2 Trie Structure: root c a ALGORITHM STEPS 1 Build Trie Insert all words, track count at each node 2 For Each Removal Simulate removing word[i] from the trie counts 3 Find LCP Length Find deepest node with count >= k 4 Store Result answer[i] = max depth with k strings sharing Example: Remove "card" (i=2) Remaining: cat, car, care "car" & "care" share "car" but "cat" differs at pos 2 LCP for k=2: "ca" (len=2) FINAL RESULT Output Array: [3, 3, 2, 3] Breakdown: i=0: Remove "cat" --> car,card,care 3 i=1: Remove "car" --> cat,card,care 3 i=2: Remove "card" --> cat,car,care 2 i=3: Remove "care" --> cat,car,card 3 OK - Verified! Time: O(n * L * 26) Space: O(n * L) Key Insight: Use a Trie with word counts at each node. When removing word[i], temporarily decrement counts along its path. The LCP for k strings is the deepest node where count >= k. This avoids rebuilding the entire structure for each removal, achieving efficient O(n * L) per query instead of O(n^2 * L). TutorialsPoint - Longest Common Prefix of K Strings After Removal | Trie-Based Optimization
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