Profile

Unblock all features

Sign in to track progress and visualise your code.

ntree.ai
Helper data structures and core patterns

Hash table

You should use a hash table whenever you need a constant time access to an element in a collection.

There are two types of hash tables. A hash set keeps values and tells whether a value is in it. In some languages, a built-in implementation is called Set.

a set keeps every value once

A hash map keeps pairs of a key and a value and gives the value of a key. In some languages, a built-in implementation is called Dictionary.

→
→
a map keeps one value for every key

Time complexity

operationtime
add an elementO(1)O(1) on average
look up an elementO(1)O(1) on average
remove an elementO(1)O(1) on average

Implementation

We will implement a hash set as an example, but a hash map works the same way, except that it also keeps a value next to every key.

Hash function

A hash set stores its elements in an array where each element gets its own index according to its value with a hash function.

A hash function turns a value into a number, and it always gives the same number for the same value. This way, using the same hash function, we can always know at which index the element is and access it in constant time.

Programming languages usually have built-in hash functions, but as an example we can assume some simple hash function that returns the length of a string, so hash("cat") is 3.

The hash can be bigger than the array, so we take it modulo the array length to get an index within its bounds.

0
1
2
3
4
index = hash(value) % 5

Collisions

What if different values produce the same hash? In this case we should store both of them at the same index in one list. So the access to this element would iterate the whole list at that index.

This is why we say it is O(1)O(1) on average, because in the worst case, when all the elements land on the same index, the time complexity is O(n)O(n), though it is usually avoided with a good hash function.

0
1
2
3
4
index = hash(value) % 5

Growth

With more elements added, more collisions will happen and it will get slower. So when the number of elements approaches the array's size, we should migrate all the elements to a new, bigger array.

Build it

Implement add, contains and remove in the class below. Use hash and grow functions that are already implemented. Call grow from add when the set holds more than 3/4 of the total capacity.

Build a hash set
Python
class HashSet:
def __init__(self, capacity: int = 4) -> None:
self.buckets = [[] for _ in range(capacity)]
self.size = 0
def add(self, value: str) -> None:
# Add the value when it is not in the set yet
pass
def contains(self, value: str) -> bool:
# Return True when the value is in the set
return False
def remove(self, value: str) -> None:
# Remove the value when it is in the set
pass
def _hash(self, value: str) -> int:
return hash(value) % len(self.buckets)
def _grow(self) -> None:
values = [value for bucket in self.buckets for value in bucket]
self.buckets = [[] for _ in range(len(self.buckets) * 2)]
self.size = 0
for value in values:
self.add(value)
animals = HashSet()
for animal in ["cat", "dog", "emu", "owl", "elk"]:
animals.add(animal)
animals.remove("cat")
print(animals.contains("cat"), animals.contains("dog"), animals.contains("elk"), animals.size, len(animals.buckets))
Was this lesson helpful?