Ctrl K

Shared Prefix After a Removal

Hard
You are given a list of words words and an integer group. For every index i, imagine removing words[i] from the list, then pick any group of the remaining words (at different indices; the words themselves may repeat) so that their common prefix, the longest prefix shared by all of them, is as long as possible. Return an array answer where answer[i] is the length of that longest common prefix after removing the i-th word. If fewer than group words remain, answer[i] = 0.
Example 1
words=["cart", "care", "cat", "dog"], group=2 → [2, 2, 3, 3]

Without cart, the best pair is care and cat, sharing ca (2). Without care, it is cart and cat (2). Without cat or dog, cart and care remain, sharing car (3).

Example 2
words=["sun", "sun", "moon"], group=3 → [0, 0, 0]

Any removal leaves two words while three are needed, so every answer is 0.

Example 3
words=["ab", "ab", "ab"], group=2 → [2, 2, 2]
Constraints
  • 1 ≤ group ≤ len(words) ≤ 10⁵
  • 1 ≤ len(words[i]) ≤ 10⁴
  • The total length of all words is at most 10⁵
  • Words consist of lowercase English letters
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsEvery Way to Space the Words HardWords Hidden in a Letter Grid HardGlued Into a Palindrome HardMirror Word Blocks HardWords Built From Shorter Words Hard
loading Python…
Input
words=["cart", "care", "cat", "dog"], group=2
Expected
[2, 2, 3, 3]

Run checks the first 3 tests in your browser. Submit checks all 198 tests on the server, hidden ones included.