0

Before starting, I want to say that I understand time complexity, and I understand how a hash table is considered O(1) vs an array having a time comp. of O(N) in terms of what you learn. What I don't understand is why looking up something in a hash table is not O(N).

Surely, just because you know the key, you still have to look your way through the data structure to find it. An analogy might be to knowing someone's name in order to find their phone number in a phone book: you can't just open the book exactly on their name; you still have to work your way through to find their location.

Tl;dr: I want to know how a hash table can retrieve a value without having to look for said value through all the keys:values before it.

Jake Jackson
  • 156
  • 1
  • 7

2 Answers2

3

The thing is, a hash table opens the "book" exacty (or at least close by, in some terms) where it needs to.

The better analogy is like accessing a list of values with an index: If you have a book list of $100$ people and their phone numbers, and you want the $37$'th person's number, you know exactly where to search it in the book - you don't have to go through all of it.

This is exactly what a hash table does: it encodes the "name" into an index using a hash function.

nir shahar
  • 11,753
  • 3
  • 17
  • 35
-1

In a hash table, we take the key, and then from the key we calculate at which place in the table it should be stored. So you just look at that single place, and usually that's where the key is stored.

It's a bit more complicate. Since there are more possible keys than entries in the table, there must be keys that "should" be stored in the same place. So it is possible that a different key is stored in that place. So there is a second formula that calculates alternative places for the key, and they will be visited until the key is found or an empty space (which means the key is not there).

If you make the table large enough compared to the number of keys stored, you will have an average of two or less accesses.

gnasher729
  • 32,238
  • 36
  • 56