1. Home
  2. Explore
  3. Computer Science
  4. Hashing and Hash Tables

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Hashing and Hash Tables

Speaker 1Speaker 2

Hashing and Hash Tables

11:42
0:00-11:42
  1. Corey

    Imagine a library containing one million randomly positioned books. If you search for a title by checking books one at a time, you might examine hundreds of thousands before finding it. That is linear search, and its search time grows as the number of books grows.

  2. Maria

    Hashing offers a different approach. Instead of walking through every previous book, we give the book's title to a tool that calculates its exact position in the library. In algorithms and data structures, that tool is based on hashing.

  3. Corey

    Hashing is the process of converting a key into a fixed-size value. For example, the key could be the string "inside code," and the hashing process might produce the number 29. That resulting number is called the hash.

  4. Maria

    The reason this is useful is that the hash can represent an index in an array. In the library example, the book title is the key, the book itself is the value, the library is the array, and the index is the book's position.

  5. Corey

    There is one essential rule: when we insert a book, we must place it at the position calculated from its title. Later, when we search for that title, hashing produces the same position, so we know where to look.

  6. Maria

    A data structure that stores these associations is called a hash table. It stores key/value pairs, with values placed in an array of slots. To find the value associated with a key, we hash the key and use the result as the array index.

  7. Corey

    The calculation itself is performed by a hash function. A hash function takes a key as input, performs computations, and returns its hash. There are many possible hash functions, and we can even create one ourselves.

  8. Maria

    Suppose our table has m slots. The hash function needs to return an index from 0 through m minus 1. A simple function for a string is to add the ASCII code of every character and then take the result modulo m.

  9. Corey

    For the string "inside code," the ASCII values add up to 1079. If m equals 30, then 1079 modulo 30 is 29. So this function assigns the key "inside code" to index 29.

  10. Maria

    That example also illustrates determinism. A hash function must always return the same hash for the same key. Otherwise, a key could be placed at one index during insertion and produce a different index during search, making the value impossible to find.

  11. Corey

    Hash tables are useful whenever keys identify associated values. In a phone agenda, a person's name can be the key and the phone number the value. In a word counter, the key is a word and the value is its number of occurrences.

  12. Maria

    A dictionary is another example: the key is a word and the value is its definition. To retrieve the definition, we hash the word and inspect the corresponding table location.

  13. Corey

    But the library analogy hides an important problem. Different keys can produce the same index. For example, "Samy Sterious" might hash to 14, and "Khaled Anas" might also hash to 14.

  14. Maria

    That situation is called a collision: two different keys produce the same hash value. Since one array slot cannot simply hold two separate values in the basic arrangement, a hash table needs a collision-handling strategy.

  15. Corey

    The first strategy is separate chaining. Instead of making each slot hold just one value, each slot holds a linked list. Every key/value pair whose hash points to that slot is stored as a node in the list.

  16. Maria

    So if three keys hash to index 13, slot 13 contains a linked list of length three. In the phone agenda, both "Samy Sterious" and "Khaled Anas" can be stored in the linked list at index 14.

  17. Corey

    The nodes must contain both the key and the value. If a list at index 14 held only two phone numbers, we would know that Khaled's number was one of them but not which one. By storing the keys, we can search the list for "Khaled Anas" and then return the matching number.

  18. Maria

    The second strategy is open addressing. It keeps at most one value in each table slot. When the intended slot is occupied, the table probes alternative slots until it finds the value or an available location.

  19. Corey

    One form is linear probing. If Khaled's hash is 14 but slot 14 is occupied, we check 15, then 16, then 17, continuing until an empty slot is found. The key still needs to be stored with the value so searches can distinguish entries encountered during probing.

  20. Maria

    Collisions usually cannot be eliminated completely. A table with m slots has only m possible hash values, while the number of possible keys, such as strings, can be unlimited. By the pigeonhole principle, if enough different keys are inserted, some must share a slot.

  21. Corey

    There is a special case called perfect hashing. If the number of known keys does not exceed the number of table slots, it may be possible to find a hash function that maps every key to a different slot. For example, 20 known keys could potentially be mapped without collisions into 30 slots.

  22. Maria

    More generally, the goal is to minimize collisions with a good hash function. A poor function might send most keys to only the first five of 30 slots, creating many collisions there. A better function distributes keys as evenly as possible, so each hash value has roughly the same probability of appearing.

  23. Corey

    Table size matters too. If a table has 10 slots but must store 50 keys, even a good hash function leads to about five elements per slot on average. The problem is insufficient space, so the table needs more slots.

  24. Maria

    That expansion process is called rehashing. We create a new table with more slots, often twice as many, and insert every existing key/value pair into the new table. Because the index is calculated using the table capacity, the entries are redistributed across the larger range.

  25. Corey

    To decide when to rehash, we examine how full the table is using the ratio n divided by m, where n is the number of stored elements and m is the number of slots. If n is 21 and m is 30, the ratio is 0.7.

  26. Maria

    For open addressing, n cannot exceed m because each slot holds at most one element, so the ratio ranges from 0 to 1. With separate chaining, multiple elements can occupy one slot's linked list, so n can exceed m; a ratio of 2.5, for example, means 50 elements stored across 20 slots.

  27. Corey

    The load factor is the maximum allowed value of n divided by m before rehashing. With a load factor of 0.75 and 100 slots, inserting the first 75 elements is acceptable, but inserting element 76 triggers rehashing.

  28. Maria

    A lower load factor means more slots relative to elements, fewer collisions, and better time efficiency, but it uses more space. A higher load factor saves space but creates more collisions and can reduce time efficiency. So choosing the load factor is a time-versus-space tradeoff.

  29. Corey

    The simple ASCII-sum function has weaknesses. It ignores character order, so "abc" and "acb" receive the same hash because their character codes have the same sum. Also, for strings of at most 20 alphabetical characters, the sum cannot exceed 2440.

  30. Maria

    That upper bound creates another problem. If the table has 2500 slots, indexes after 2440 can never be reached by that function, so rehashing to an even larger table does not reduce collisions in the usable region. A better function should distribute keys effectively across the available range and should be computationally efficient.

  31. Corey

    Hashing also has applications beyond hash tables, including cryptography. But in this discussion, the key point is that hashing calculates where associated values should be stored.

  32. Maria

    Let's connect the ideas to a separate-chaining implementation. A node contains a key, a value, and a pointer to the next node. Each table slot contains a linked list, and the linked list needs methods to insert, search, and delete nodes.

  33. Corey

    Insertion into the linked list can happen at the beginning: create a node whose next pointer is the current head, then make that node the new head. Searching traverses the nodes until it finds the requested key, and deletion searches for the target and skips over it when found.

  34. Maria

    The hash table itself needs a capacity, a size, a load factor, and an array of linked-list slots. Its main operations are hashing, rehashing, inserting or updating a key/value pair, checking whether a key exists, retrieving its value, and deleting it.

  35. Corey

    When inserting, we hash the key, select its linked list, and search for that key. If the key already exists, we update its value rather than adding a duplicate key. If it does not exist, we insert a new node, increase the size, and rehash if the load factor has been exceeded.

  36. Maria

    Lookup follows the same path: calculate the index, search that slot's list, and report whether a matching node exists. Getting a value returns the node's value if the key is found, or null if it is not. Deletion hashes the key, removes it from the appropriate list, and decreases the size when removal succeeds.

  37. Corey

    The linked-list operations help explain the time complexity. Inserting at the head takes O(1), while searching or deleting takes O(l), where l is the length of the relevant linked list. The hash calculation is treated as O(1) with respect to the number of elements in the table, although its cost can depend on key size in some situations.

  38. Maria

    For separate chaining, the best case has no collisions, so lists have length zero or one and operations take O(1). The worst case puts all n elements in one list, producing O(n) search, insertion, or deletion behavior. A good hash function and rehashing aim to keep lists short, so these operations are O(1) on average.

  39. Corey

    Rehashing itself takes O(n) because all existing elements must be traversed and inserted into the new table. However, it happens only occasionally, after the load factor is exceeded. Spread across many insertions, the average cost of rehashing is O(1) per insertion; this is called amortized complexity.

  40. Maria

    Therefore, with a good implementation, insertion is O(1) on average and amortized, lookup is O(1) on average, getting a value is O(1) on average, and deletion is O(1) on average. The worst case for these operations remains O(n), which is why hash-function quality and table management matter.

  41. Corey

    The table's space complexity is O(n). There are n nodes for n stored elements, and the number of slots is a constant multiple of n determined by the load factor. Adding those two sources of storage still grows linearly with the number of elements.

  42. Maria

    This explains why hash tables can be preferable to a simple array for key/value operations: they provide average constant-time insertion, lookup, retrieval, and deletion. Many languages provide built-in versions, such as Python's dict, Java's HashMap, and C++'s unordered_map.

  43. Corey

    A classic algorithmic use is the two-sum problem: find two array elements whose sum is k. Trying every pair takes O(n²), but a hash table can store each value along with its index; when processing x, we check whether k minus x has already appeared. This reduces the solution to O(n).

  44. Maria

    Finally, keys and values have different requirements. Keys must be unique, although different keys may have the same value. Keys must also be immutable, because changing a key after insertion could cause the hash function to produce a different result and send searches to the wrong location.

  45. Corey

    Immutable types such as integers, strings, and tuples can serve as keys, while mutable objects such as arrays and sets cannot safely serve as keys in this context. Values do not need to be unique or immutable; they can be integers, strings, arrays, hash tables, or other objects.

  46. Maria

    So the complete picture is this: hashing converts a key into a fixed-size hash, a hash function performs that conversion deterministically, and a hash table uses the result to locate a value. Collisions are handled with separate chaining or open addressing, rehashing controls overcrowding, and good distribution is what makes the structure fast on average.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent