Skip to content
BytePatterns

Shortest Unique Prefixes

MediumTries#trie#prefix-count~25m

Problem

Given a list of distinct lowercase words where no word is a prefix of another, return for each word the shortest prefix that no other word in the list starts with. This is how a command line lets you type just enough letters to pick one command.

Examples

Input:  words = ["zebra", "dog", "duck", "dove"]
Output: ["z", "dog", "du", "dov"]
Why:    d is shared by three words and do by two, but dog and dov are unique
Input:  words = ["bear", "bell", "bid", "bull", "buy"]
Output: ["bea", "bel", "bi", "bul", "buy"]
Input:  words = ["solo"]
Output: ["s"]
Why:    edge case, a single word is identified by its first letter

Hints

0 / 3

Stuck on the idea rather than the code? Trie vs Hash Set covers it.