How can I design an algorithm which can return the 10 most frequently used words in a document in O(n) time? If additional space can be used.
I can parse and place the words in a hash map with count . But next I have to sort the values to get the most frequent ones . Also I have to have a mapping btw the values -> Key which cannot be maintained since values may be repeating.
So how can I solve this ?
It may be done in O(n) if you use the correct data structure.
Consider a
Node, consisting of 2 things:Node. All the pointers are initially set toNULL.Create a root node. Define a “current”
Nodepointer, set it to root node initially.Then walk through all the characters of the document and do the following:
NULL– allocate it. The currentNodepointer is updated.Node. Then reset the “current”Nodepointer to point to the root node.By such you build a tree in O(n). Every element (both node and leave) denote a specific word, together with its counter.
Then transverse the tree to find the node with the largest counter. It’s also O(n), since the number of elements in the tree is not bigger than O(n).
Update:
The last step is not mandatory. Actually the most common word may be updated during the character processing.
The following is a pseudo-code: