KatInterview

Minimal Distinguishing Abbreviations for a Word List

StringsAuto-graded · 22 test cases
MediumAuto-gradedStringstrieprefixhash-map

Last 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 a to z.
  • 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.