How to compute shortest unique prefixes of a set of strings?
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
The shortest unique prefix of a string is the smallest prefix that distinguishes it from every other string in the set. This problem appears in autocomplete systems, command-line abbreviation, routing tables, and compact identifiers.
The standard solution is a trie, also called a prefix tree. The trie lets you count how many words pass through each prefix, and the first node with count 1 marks the shortest unique prefix.
Trie-Based Solution
Insert every word into a trie and increment a frequency counter on each node you visit. Then, for each word, walk through the trie again until you reach a node whose frequency is 1. The path to that node is the answer.
Output:
Notice that cat needs the full word here, not just ca, because car and cart also share ca.
Why the Trie Works
Every node in the trie corresponds to a prefix. The node count tells you how many words share that prefix.
For example, with car and cart:
- Prefix
cis shared. - Prefix
cais shared. - Prefix
caris still shared because one word is a prefix of the other. - '
cartbecomes unique only atcart.'
This highlights an important detail: when one word is a full prefix of another, the shorter word may need its complete length and still not be unique under some definitions. Many interview and algorithm problems assume the full word is acceptable as the shortest distinguishing output, even if another word extends it.
Complexity
Let N be the number of words and L be the total number of characters across all words.
- Building the trie takes
O(L)time. - Extracting all prefixes also takes
O(L)time. - Space usage is
O(L)in the usual implementation.
That is usually better than comparing every word with every other word, which can degrade toward quadratic behavior.
A sort-based solution also exists: sort the strings lexicographically, then compare each word only with its immediate neighbors. That approach is elegant and often simpler when memory matters. The trie is still the most direct structure if you want prefix queries beyond this single task.
Handling Duplicates and Definitions
You need to decide what “unique” means for duplicate strings. If the input contains the same word twice, no prefix can distinguish the copies from each other. In that case you either return the whole word for both, include multiplicity in the answer format, or reject duplicates as invalid input.
You should also define how to treat a word that is a prefix of another word. Some systems add an end-of-word marker and treat the full shorter word as unique because the terminal marker distinguishes it internally. Others require an external disambiguation rule.
Common Pitfalls
A common mistake is forgetting to increment counts on every traversed node. If counts are updated only at leaf nodes, the algorithm cannot tell which prefixes are shared.
Another bug is returning too early for words that are prefixes of other words. Test cases like car and cart are essential because they reveal whether your definition of uniqueness is consistent.
Developers also sometimes use a trie when sorting would be simpler for one-off batch computation. The trie is excellent, but it is not the only correct method.
Finally, if the alphabet is large, avoid fixed-size child arrays unless you have a strong reason. Dictionaries or maps are usually more practical.
Summary
- A shortest unique prefix is the smallest prefix that identifies one string within the set.
- The standard solution is a trie with per-node frequency counts.
- The first trie node with count
1gives the answer for a word. - Total time is linear in the total number of characters.
- Be explicit about duplicate strings and prefix-of-another-word edge cases.
Related reading
- How to compute the absolute minimum amount of changes to convert one sortorder into another?
- How to compute the union polygon of two or more rectangles
- How to convert a binary tree to binary search tree in-place, i.e., we cannot use any extra space
- How to convert an integer to a string in any base?
- How to compute the intersection points of a line and an arbitrary shape?
- how to convert logits to probability in binary classification in tensorflow?
- How to convert an RGB color to the closest matching 8-bit color?
- How to convert known connected component to adjacency matrix with tensor manipulations only?

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.