Shortest Unique Prefix Finder - Problem
Given a list of words, find the shortest prefix for each word that uniquely identifies it from all other words in the list.
A unique prefix is the minimum number of characters from the beginning of a word that makes it distinguishable from every other word in the list. If a word is a prefix of another word, the entire word itself is the shortest unique prefix.
Return an array of strings where each string is the shortest unique prefix for the corresponding word at the same index.
Input & Output
Example 1 — Basic Words
$
Input:
words = ["cat", "car", "card", "dog"]
›
Output:
["cat", "car", "card", "d"]
💡 Note:
'cat' needs full word to distinguish from 'car'/'card', 'car' needs full word to distinguish from 'card', 'card' needs full word, 'dog' only needs 'd' since no other word starts with 'd'
Example 2 — Prefix Overlaps
$
Input:
words = ["apple", "app", "application"]
›
Output:
["appl", "app", "appli"]
💡 Note:
'apple' needs 'appl' to distinguish from 'app'/'application', 'app' is complete word so needs full 'app', 'application' needs 'appli' to distinguish from others
Example 3 — Single Character Differences
$
Input:
words = ["a", "aa", "aaa"]
›
Output:
["a", "aa", "aaa"]
💡 Note:
Each word is a prefix of the next, so each word needs its full length to be unique
Constraints
- 1 ≤ words.length ≤ 1000
- 1 ≤ words[i].length ≤ 200
- words[i] consists of lowercase English letters
- All words are distinct
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code