VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-all-shortest-unique-prefixes-to-represent-each-word-in-a-given-list/

⇱ Find shortest unique prefix for every word in a given list (Using Trie) - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find shortest unique prefix for every word in a given list (Using Trie)

Last Updated : 23 Jul, 2025

Given an array of words, the task is to find the shortest unique prefixes to represent each word in the given array. Assume that no word is prefix of another. 

Examples: 

arr[] = {"zebra", "dog", "duck", "dove"}
Output: z dog du dov
Explanation:
z => zebra
dog => dog
duck => du
dove => dov

arr[] = {"geeksgeeks", "geeksquiz", "geeksforgeeks"};
Output: geeksg geeksq geeksf

A Simple Solution is to consider every prefix of every word (starting from the shortest to largest), and if that is not a prefix of any other string, then print it. 

Approach:

The idea is to use trie and maintain a frequency count at each node representing how many words pass through that node. For each word, we traverse the trie along its path until we find a node with frequency 1, indicating no other word shares this prefix - the index at this point gives us the ending index of our minimum unique prefix.

Step-by-step approach:

  • Build a trie with all words and maintain frequency count at each node
  • For each word, traverse the trie until finding a node with frequency 1 to get its unique prefix 
  • Create substring from start to end index of found prefix and add to result

Trie Illustration:

👁 trie
trie



Output
z dog du dov 

Time Complexity: O(n*m) where n is the length of the array and m is the length of the longest word.
Auxiliary Space: O(n*m) 


Comment
Article Tags: