Shortest Unique Prefix
Master this topic with zero to advance depth.
Shortest Unique Prefix
Given an array of words, find the shortest unique prefix of each word, such that the prefix is not a prefix of any other word.
Visual Representation
Words: ["zebra", "dog", "duck", "dove"]
Trie with counts:
root
-> z(1) -> e(1) ... -> found count=1 at 'z'
-> d(3)
-> o(2)
-> g(1) -> found count=1 at 'g' (prefix "dog")
-> v(1) -> found count=1 at 'v' (prefix "dov")
-> u(1) -> found count=1 at 'u' (prefix "du")Examples
Level I: Brute Force Comparison
Intuition
For each word, check every possible prefix starting from length 1. Compare this prefix against all other words. The first prefix that is not a prefix of any other word is the shortest unique prefix for that word.
Level III: Trie (Node Visited Count)
Intuition
Insert all words into a Trie. As you insert, increment a visited count (count) for each node along the path. To find the shortest unique prefix for a word, traverse the Trie until you reach a node with count == 1. That node marks the end of the shortest unique prefix.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.