1220. Shortest Distinguishing Prefixes
A contacts app wants the shortest abbreviation of each name that no other entry in words starts with. For each word, return its shortest prefix that is not a prefix of any other word in the list (another entry at a different index). If no such prefix exists, because the word is equal to another entry or is itself a prefix of another entry, the word is returned in full.
Return the answers in the input order. Sort the words, compute the longest common prefix of each word with its two sorted neighbours, and keep the first min(length, 1 + larger common prefix) characters. Duplicated words are neighbours after sorting.
Here 1 <= words.length <= 10^5, 1 <= words[i].length <= 20, and words use lowercase letters. The intended cost is O(n L log n) time and O(n L) space for words of length at most L.
Example 1
- Input:
- words = ["apple","apply","apt","bat"]
- Output:
- ["apple","apply","apt","b"]
- Explanation:
apple and apply differ only in the last letter, so each needs its whole word; apt needs all three letters because ap is shared; b alone is unique.
Example 2
- Input:
- words = ["zebra","zoo","zeal","zebra"]
- Output:
- ["zebra","zo","zea","zebra"]
- Explanation:
The two zebra words are equal so each returns itself; zoo needs zo, and zeal needs zea because zebra also starts with ze.
Example 3
- Input:
- words = ["x"]
- Output:
- ["x"]
- Explanation:
A lone word has no other word to clash with, and its shortest prefix is its first letter, which is the whole word.
Constraints
1 ≤ words.length ≤ 105
1 ≤ words[i].length ≤ 20
words contain lowercase letters only
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 8,000 msC++ 2,000 msJava 4,000 msJavaScript 4,000 msTypeScript 4,000 ms
Expected complexity
- Time
- O(n * L * log n)
- Space
- O(n * L)