Hash algorithms

A good hash spreads evenly · Part of Lists, stacks and hash

Key idea

Practice

6 questions · about 3 min

Explained step by step

Hash function

Chaining and probing keep the table working when there are collisions, but they don't reduce them. What decides how many collisions there are is the hash algorithm. A good algorithm does 3 things: it's deterministic, meaning the same key always gives the same hash; it's fast to compute; and it spreads keys evenly across the buckets. If every key landed in 1 bucket, the table would be a list: O(n).

Hash algorithms are useful for much more than tables. For storing passwords: the system doesn't store the password but its hash, and when you log in it compares the hash of what you typed with the stored one. For checking that a file arrived intact: the file is sent with its hash, and the receiver computes the hash of what arrived; if they match, nothing changed along the way.

For security uses, like passwords, a hash needs 3 more properties. One-way: from the hash you can't figure out the input. Collision resistance: it must be nearly impossible to find 2 different inputs with the same hash. And the avalanche effect: a tiny change in the input changes the result hugely and unpredictably. Spreading evenly isn't enough: key % 100 spreads evenly, but anyone can find 2 keys that collide.

Many hash algorithms end by taking the remainder of dividing by a large number, and it's best for it to be prime. If the modulus has divisors and the keys follow a pattern, they pile up. With modulus 9, the keys 0, 3, 6, 9, 12... give only 0, 3 and 6: they use 3 buckets out of 9. With modulus 13, which is prime, the same keys give 0, 3, 6, 9, 12, 2, 5, 8...: they use them all. That's why a large prime is usually used, like 1,000,000,007.

SHA-256

Simple hash algorithms, like adding up the letters' codes, are fragile: "ab" and "ba" add up to the same and collide. In practice, standard algorithms like MD5, SHA-1, SHA-2 and SHA-3 are used, which turn any input into a fixed-length hash. MD5 and SHA-1 have been successfully attacked and aren't used for security. SHA-256, from the SHA-2 family, is still secure and among the most widely used.

Hash table

A hash table's keys can be numbers, texts or other types, and each language knows how to compute their hash. In Python, an integer's hash is the number itself. But in many languages only objects that don't change can be used as keys: if you used a list as a key and changed it, its hash would change and you'd no longer find it in its bucket. Also, Python mixes the hash of texts with a random value every time it starts, so nobody can craft keys that collide on purpose.

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

A good hash spreads evenly