![]() |
VOOZH | about |
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 => dovarr[] = {"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:
Trie Illustration:
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)