It is a google interview question and I find most answers online using HashMap or similar data structure. I am trying to find a solution using Trie if possible. Anybody could gi
The first thing to note is that you can completely ignore the letter order.
Have a trie (well, sort of a trie) as follows:
Build the trie like this:
For each word, sort the letters of this word and insert the sorted letters into the trie (by creating a path of these letters from the root), creating all required nodes as you go. And store the word at the final node.
How to do a look-up:
For a given set of letters, lookup all subsets of letter (most of which hopefully won't exist) and output the words at each node encountered.
Complexity:
O(k!)
, where k
is the number of supplied letters. Eek! But luckely the less words there are in the trie, the less of the paths will exist and the less time this will take. And k
is the number of supplied letters (which should be relatively small), not the number of words in the trie.
Actually it may be more along the lines of O(min(k!,n))
, which looks a lot better. Note that if you're given enough letters, you'll have to look up all words, thus you have to do O(n)
work in the worst case, so, in terms of the worst case complexity, you can't do much better.
Example:
Input:
aba
b
ad
da
la
ma
Sorted:
aab
b
ad
ad
al
am
Trie: (just showing non-null children)
root
/ \
a b
/-/|\-\
a b d l m
|
b
Lookup of adb
:
a
b
d
ad
and da
b
b
a
child, as only children >= b
existsd
child, returnd
child, stop