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
INPUTALGORITHMRESULTcatcarcarddogWords array1Build trie structure2Count word frequencies3Traverse to count=14Extract unique prefixesTrie with counts:c(3)→a(3)→[r(2),t(1)]d(1)catcarcarddUnique prefixesKey Insight:A trie with frequency counts lets us identify unique prefixes in a single traversal,stopping as soon as we reach a node with count=1 (only one word passes through).TutorialsPoint - Shortest Unique Prefix Finder | Trie Solution
Asked in
Google 42 Microsoft 38 Amazon 35 Facebook 28
28.4K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen