Perl Weekly Challenge 057: Invert Tree and Shortest Unique Prefix
Shortest Unique Prefix
Write a script to find the shortest unique prefix for each each word in the given list. The prefixes will not necessarily be of the same length.Sample Input
[ "alphabet", "book", "carpet", "cadmium", "cadeau", "alpine" ]Expected Output
[ "alph", "b", "car", "cadm", "cade", "alpi" ]
Let me start with the second task as it was definitely simpler (at least for me).
We iterate over all the input words. For each word, we try to find the shortest prefix possible. To know what prefixes have already been used, we keep two hashes: one stores the abandoned prefixes (i.e. those that were not unique anymore), the second one stores the “current” prefixes (the prefix is the key, the actual word is the value). We start from length 1 and add 1 in each step. If the prefix isn’t used and hasn’t been used, we assign it to the word and proceed to the next word. If the prefix is currently used for a different word, we store the prefix as “used” and prolong the prefix for the old word by one—but we continue the loop for the current word, in case their common prefix is longer.



