Skip to main content
3 of 6
added 97 characters in body
Vitaly Olegovitch
  • 1.2k
  • 1
  • 14
  • 21

Hash table is very good if you have few words that are repeated many times.

Let's suppose that your hash function is very good, that means that the distribution of elements inside various buckets is close to the uniform distribution. Even in that case, if the number of buckets is much smaller than the number of elements inside the table, the execution time of search in hash tables is $O(n)$, where $n$ is the number of different words that you have found.

This happends because each bucket is a simple list and if inside a bucket you will have $k$ elements, the cost of the search would be the sum of the cost to calculate hash function plus the cost to find the right bucket plus the cost to find the right element inside the list. The first two costs are $O(1)$ the last one is $O(k)$ because you are performing linear search.

If you have few elements and lots of buckets, $O(k)$ will be close to $O(1)$, otherwise it will be close to $O(n)$ as stated above.

I think that the best data structure that you could use is the Self-balancing binary search tree, it would have $O(\log n)$ time to insert and $O(\log n)$ time to search.

Vitaly Olegovitch
  • 1.2k
  • 1
  • 14
  • 21