Hash tables

From key to slot in 1 calculation · Part of Lists, stacks and hash

Key idea

Practice

6 questions · about 3 min

Explained step by step

Hash table

A hash table stores key-value pairs: for example, the student ID as key and the name as value. Given the key, it returns the value in O(1). Lookup, insertion, deletion and update are O(1). In an unsorted array or list, adding at the end is O(1), but lookup and deletion are O(n), because you have to walk through. It's like a coat check: you get a number and with that number you get your coat back without checking all 300.

Besides lookup, insertion and deletion, a hash table can be walked in 3 ways: by key-value pairs, by keys only or by values only. Walking is O(n), because you visit every element. What a hash table doesn't give you is order: pairs come out in bucket order, not in the order they were added nor sorted by key. If you need order, you use another structure, like a search tree.

Hash tables show up whenever you need to find something by a key fast. Counting how many times each word appears in a text, knowing whether you've already seen an element, keeping a cache of results or indexing users by email. In Python it's the dict, in Java the HashMap. The price is the extra memory for the buckets and that it keeps no order.

Hash function

A simple hash table is an array: each slot is called a bucket and holds a key-value pair. To know which bucket a key goes in, a hash function is used, which does 2 steps: it computes a number from the key, the hash value, and takes the remainder of dividing by the number of buckets. If there are 100 buckets and a student ID's hash is the ID itself, the bucket is ID % 100: student 12836 goes to bucket 36.

Collision

A hash function turns a huge world of possible keys into a few buckets, so inevitably 2 different keys can land in the same one: that's a collision. With hash % 100, student 12836 and student 20336 both land in bucket 36, and if the table holds just 1 pair per bucket, one overwrites the other. Collisions are unavoidable: what you do is handle them and keep them rare.

Load factor

With more buckets, it's less likely 2 keys land in the same one, so growing the table reduces collisions. But growing costs: every pair has to move to the new table and its bucket must be recomputed, because the capacity changed. To decide when, the load factor is used: elements divided by buckets. In Java, when it passes 0.75, the table doubles.

Terms in this lesson

Arki, the beaver mascot

Your next interview starts with 5 minutes today.

Free on iOS and Android. Start from zero, no account needed.

Key idea

From key to slot in 1 calculation