Save 25%Black Friday: 25% off all plans — use code BLACKFRIDAY2026 at checkout. Ends Friday, Dec 4.Claim the deal

Given a list of words, find the shortest unique prefix for each word such that the prefix uniquely identifies it among all words. The shortest unique prefix is the minimum starting substring that differentiates the word from the rest. Return the result list in the same order as the input.

Constraints

  • 1 ≤ words.length ≤ 10⁵
  • 1 ≤ words[i].length ≤ 100
  • Each word consists only of lowercase English letters ('a' - 'z').
  • No word in the list is a prefix of another, ensuring each word can have a unique prefix.

Example 1:

Input: words = ["zebra", "dog", "duck", "dove"] Output: ["z", "dog", "du", "dov"] Explanation: For "zebra", since no other word starts with 'z', the unique prefix is "z". For "dog", the letter "d" is common with "duck" and "dove", so the prefix is extended to "dog". Similarly, "duck" requires "du" and "dove" needs "dov" to be uniquely identified.

Example 2:

Input: words = ["codetest", "code", "coder", "coding"] Output: ["codet", "code", "coder", "codi"]

Example 3:

Input: words = ["a", "ab", "aab", "abc", "aabc", "def"] Output: ["a", "ab", "aab", "abc", "aabc", "d"]


Accepted
2.6k/5.1k
Acceptance Rate50.7%
Test Cases
Input
words =
Output
Expected