Bitpath

Lesson 1 · Unit 04

Hash, then bucket

From a key to an array index, and what happens when two keys collide

13 exercisesabout 3 min

What you practise

  • Hash function, modulo, collisions, chaining

Try a question from this lesson

Pick one

A cloakroom has 10 hooks, numbered 0 to 9. Your ticket says 47. The attendant walks straight to your coat without searching. Which rule makes that possible?

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Hash, then modulo

A hash table keeps its items in an array of buckets. To choose a bucket it turns the key into a number, the hash, then takes that number modulo the number of buckets.

The same key always gives the same bucket, so a lookup goes straight to it.

def bucket(key, capacity):
    total = 0
    for ch in key:
        total += ord(ch)   # char code
    return total % capacity

print(bucket("ab", 8))      # 195 % 8
function bucket(key, capacity) {
  let total = 0;
  for (const ch of key) {
    total += ch.charCodeAt(0);
  }
  return total % capacity;
}
console.log(bucket("ab", 8)); // 195 % 8
function bucket(
  key: string,
  capacity: number,
): number {
  let total = 0;
  for (const ch of key) {
    total += ch.charCodeAt(0);
  }
  return total % capacity;
}
console.log(bucket("ab", 8)); // 195 % 8

Python noteord("a") is 97, the character code. Python also has a built-in hash(), which is what dict really uses.

JavaScript note"a".charCodeAt(0) is 97. JavaScript has no public hash function: Map hashes its keys internally.

TypeScript note): number { after the parameter list is the return type. The parameters sit one per line only to keep the lines short.

Concept

Chaining: a bucket holds a list

The simplest plan for collisions is chaining. Each bucket holds a small list of key-value pairs, called a chain. Keys that collide share a chain.

A lookup hashes to the bucket, then scans that one chain for the key.

table = [[], [], [], []]   # 4 buckets
table[3].append(("ab", 1))
table[3].append(("ba", 2))   # collision
print(len(table[3]))
const table = [[], [], [], []];
table[3].push(["ab", 1]);
table[3].push(["ba", 2]); // collision
console.log(table[3].length);
type Pair = [string, number];
const table: Pair[][] = [[], [], [], []];
table[3].push(["ab", 1]);
table[3].push(["ba", 2]); // collision
console.log(table[3].length);

Python noteA pair is written as a tuple, ("ab", 1). Tuples cannot be modified, which suits a pair that is only read.

TypeScript note[string, number] is a tuple type: exactly two items, a string then a number. Pair[][] is an array of buckets, each an array of pairs.

10 more exercises in the app

  • 3× type the answer
  • 3× multiple choice
  • 1× fill the blanks
  • 1× true or false
  • 1× match the pairs
  • 1× order the lines

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy