Editorial for Facebook Hacker Cup '15 Round 2 P3 - Autocomplete Strikes Back
Submitting an official solution before solving the problem yourself is a bannable offence.
This problem can be approached in a few different ways, but the intended algorithm consists of inserting all words into a trie (while marking which nodes in the trie represent the end of a word), and then breaking the problem down into subproblems with dynamic programming. Let
be the minimum number of letters to type in order to text
different words which end at nodes in node
's subtree (or rather, subtrie). We can compute
by recursively traversing the trie, with the final answer being
.
Let's establish that depth of node
. Note that
is then also the length of the prefix (and possibly complete word) represented by node
.
To establish some simple base cases, for any node
, and
for any node
besides the root. This is because, if only
word will be used from node
's subtree, then the prefix represented by node
won't be a prefix of any other chosen word, meaning that it can be used to type this word.
For any internal node and any positive
, we can compute
by considering various distributions of
words amongst node
and its children's subtries. Consider that node
has children
, and we use
words from each of those children's subtries respectively. If node
represents the end of one of the
given words, then
, with
. Otherwise,
with
. Either way, we can consider all of the possible combinations of
with a classic instance of dynamic programming across the children. In this fashion, we can in fact compute the values
all at once in
time.
Every node is the child of at most one other node, meaning that the overall time complexity of this algorithm is , where
is the number of nodes in the trie (which is at most the sum of the lengths of the words).
Comments