A Trie (reTrieval) is a common solution to an optimal prefix search, like one you would use in an autocomplete. It therefore make sense to use it in the following problem
and here is the complete problemGiven a list of words, return the shortest unique prefix of each word.
At this point I should mention, that this post isn't about solving the problem with a Trie.
I had heard of a Trie but was not familiar with the implementation details. I therefore decided to attempt this problem without a Trie.
Understanding the problem
We are looking for prefixes that are -
- unique
- short
Drawing this out with a solution that has more than 2 characters puts the problem into perspective
Solving it
At first glance, it seemed obvious to me that I had to track the position in which each character occurred. I could use a map for this, where
- the key was the character,
- and the value was a set of positions
Revising the Solution
I would instead now keep track of the occurrences too, with a map of maps.
- The key of the outer map would be the character
- The key of the inner map would be the position
- The value of the inner map would the number of occurrences
At this point, I realized that this solution would be potentially memory intensive as it involves building up a map, and the problem statement did not list any constraints
With a revised map, I can now traverse the characters in each word.
- Characters that have more than one occurrence in the current position are saved to a candidate string
- The traversal is terminated when we find a character that has only one occurrence in the current position and hence a unique prefix. This character is added to the candidate string and that is our solution for that word.
I was curious to see if my approach was listed as an alternative solution, but most online solutions advocate the use of a Trie. I do plan on researching this some more and understanding it implementation details , and that will be a topic of an upcoming post.