Find Shortest Unique Prefixes
Company: Meta
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates string-processing skills and understanding of data structures for prefix management (e.g., tries), along with algorithmic efficiency and edge-case reasoning.
Constraints
- 1 <= len(words) <= 10^4
- 1 <= len(words[i]) <= 10^3
- The total number of characters across all words is at most 2 * 10^5
- All words are distinct
- Words contain only lowercase English letters
Examples
Input: (['zebra', 'dog', 'duck', 'dove'],)
Expected Output: ['z', 'dog', 'du', 'dov']
Explanation: 'z' only starts zebra. For dog, 'd' and 'do' are shared with other words, so 'dog' is needed. Duck is identified by 'du', and dove by 'dov'.
Input: (['alone'],)
Expected Output: ['a']
Explanation: With only one word, the first character is already unique.
Input: (['apple', 'ape', 'april', 'bat'],)
Expected Output: ['app', 'ape', 'apr', 'b']
Explanation: The three words starting with 'ap' need one more character to become distinguishable. 'bat' is uniquely identified by 'b'.
Input: (['app', 'apple', 'apricot', 'banana'],)
Expected Output: ['app', 'appl', 'apr', 'b']
Explanation: 'app' is a prefix of 'apple', so no shorter prefix uniquely identifies it and the full word is returned. 'apple' needs 'appl', 'apricot' needs 'apr', and 'banana' needs only 'b'.
Input: (['a', 'b', 'c'],)
Expected Output: ['a', 'b', 'c']
Explanation: Each one-character word is already uniquely identified by its only character.
Input: (['interview', 'internet', 'internal', 'interval'],)
Expected Output: ['intervi', 'interne', 'interna', 'interva']
Explanation: All words share 'inter'. The next characters still create pairs, so each word needs one more distinguishing character after that shared section.
Hints
- Consider building a trie where each node records how many words share the prefix represented by that node.
- For each word, walk through the trie until you reach the first node whose count is 1.