Minimal Distinguishing Abbreviations for a Word List
StringsAuto-graded · 22 test casesLast updated
Compute, for each word, the shortest leading substring shared with no other entry, using prefix counting or a trie, and return the whole word when none exists.
You are given a list of lowercase words. For each word, determine the shortest abbreviation that identifies it unambiguously. The abbreviation must be a leading portion of the word (a prefix).
A prefix of a word is called distinguishing if no other entry in the list begins with that same prefix. Entries are compared by position in the list, so if the same word appears twice, the two copies count as different entries and each one blocks the other.
For every word, in the same order as the input:
- Return its shortest distinguishing prefix.
- If no prefix qualifies (not even the whole word), return the whole word unchanged. This happens when the word is a prefix of another entry, or when it appears more than once.
Return a list of strings with the same length and order as words.
Function
def shortest_distinguishing_prefixes(words: List[str]) -> List[str]:
Constraints
0 <= len(words) <= 10^4(an empty list produces an empty list)1 <= len(words[i]) <= 100- Each word consists only of lowercase English letters
atoz. - Duplicate words may appear.
Examples
Example 1
Input: shortest_distinguishing_prefixes(['zebra', 'dog', 'duck', 'dove'])
Output: ['z', 'dog', 'du', 'dov']
Example 2
Input: shortest_distinguishing_prefixes(['apple', 'apply'])
Output: ['apple', 'apply']
Hints
Hint 1
For a prefix p of some word, ask how many entries in the list start with p. When is the answer 'only this word'?
Hint 2
Precompute, for every prefix of every entry, how many entries start with it. A hash map keyed by prefix, or a trie with a counter on each node, both work.
Hint 3
For each word, check prefixes from length 1 upward and stop at the first one whose count is 1. If the loop finishes without a hit, return the whole word; this naturally covers duplicates and words that are prefixes of others.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A prefix p of a word is distinguishing exactly when the word is the only entry in the list that starts with p. So if we know, for every prefix, how many entries start with it, the question becomes "is the count equal to 1?"
The algorithm uses two passes:
- Count. For each entry and each length
ifrom 1 to the word's length, increment a counter forword[:i]in a hash map. (A trie where each node stores the number of words passing through it is the same idea.) - Query. For each entry, in input order, look at its prefixes from shortest to longest. The first prefix whose count is 1 is the answer. If none has count 1, append the whole word.
Why it is correct
- The count of a prefix includes the word itself, so
count == 1means no other entry starts with that prefix. Duplicates are counted separately, so a repeated word never reaches count 1 and falls back to itself. - Scanning from the shortest prefix and stopping at the first match gives the shortest one.
- If even the full word has count above 1, then another entry starts with the whole word (it is a prefix of another entry, or a duplicate). The rules say to return the whole word, which is what the fallback does.
- The output is built by iterating over the input in order, so the order is preserved. An empty input yields an empty list.
Complexity
Let n be the number of words and L the maximum word length.
- Time: O(n · L²) for the hash-map version because each slice costs up to O(L). A trie version reduces this to O(n · L).
- Space: O(n · L²) for the hash map in the worst case, or O(n · L) trie nodes.
With n ≤ 10^4 and L ≤ 100 this is comfortably fast.
Reference solution
from typing import List
def shortest_distinguishing_prefixes(words: List[str]) -> List[str]:
# Count how many entries start with each prefix.
counts = {}
for word in words:
for i in range(1, len(word) + 1):
prefix = word[:i]
counts[prefix] = counts.get(prefix, 0) + 1
result = []
for word in words:
for i in range(1, len(word) + 1):
if counts[word[:i]] == 1:
result.append(word[:i])
break
else:
# No distinguishing prefix: prefix of another word or a duplicate.
result.append(word)
return result