AlgoTales · Roadmap

Hash tables

Beginner · 9 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

A hash table stores key and value pairs so that you can find a value straight from its key. A hash function converts the key into a shelf number, so you go directly there instead of checking every item. It is what powers PHP associative arrays and JavaScript objects and maps.

Practical use cases

  • Web app: Looking up a user by email at login. A login page must find the account that belongs to the typed email among 200,000 users. Looping through all users is slow. Keeping users in a keyed structure, such as a map keyed by email, takes you straight to the record, so login responds immediately.
  • Web app: Counting words or votes quickly. A poll page tallies votes per option, and a blog counts how often each tag is used. Using an associative array, each vote does counts[option]++ in one step. Counting a million items takes one pass instead of searching a list for each one.
  • System: Caches, joins and compiler symbol tables. Caches such as Redis are essentially huge hash tables. Databases use them to join tables quickly, and compilers keep a table of every variable name and what it means, looked up constantly during compilation, so a slow lookup there would slow every build.

The story: Bhaiya's Numbered Shelves

Bhaiya ran a kirana store in a busy mohalla. His memory was legendary: he knew every customer's favourite snack. But as the neighbourhood grew he began to forget, so he started writing names in a notebook. Finding "Zoya" meant flipping through hundreds of pages while a queue formed.

His niece Mira had just learned about hash functions. "Bhaiya, build seven numbered shelves. When someone gives you a name, run the little recipe to get a shelf number. Put their snack on that shelf. Next time, run the same recipe on the name, walk straight to that shelf, and there it is!"

It worked like magic. Whether the store had ten customers or ten thousand shelves' worth, finding a favourite took the same quick walk. Bhaiya had just built a hash table: a hash function to choose the shelf, plus an array of shelves to hold the items. It is why dictionary lookups in your favourite language feel instant.

How to spot this problem, and where you need it

You keep looking things up by a name, id or key in a list, and each lookup checks items one by one, so the app slows down as the data grows.

Signs you need it

  • You use in_array(), array_search() or a loop with an if to find an item by its id, email, SKU or name.
  • The task is to count occurrences, find duplicates, check "have I seen this before?" or match two lists by a key.
  • A page is fine with 100 records in testing but the same lookup takes seconds with 100,000 in production.

Where to use it in a project

  • Looking up users, products or settings by id, email or slug during a request.
  • Counting, grouping and deduplicating items while processing imports or reports.
  • Caching results of expensive calls under a key.

The solution

Put the data into a hash table (an associative array, object, Map or Set) using the thing you search by as the key. To look up, hand over the key and get the value directly. To check for existence, ask if the key is present. Build the table once before the loop instead of searching the list repeatedly inside it.

Payoff: Before: scanning 100,000 users on every lookup. After: one direct lookup, and a loop that took 30 seconds finishes in about 0.1 second.

Explain it like I am 8

Imagine a toy shelf with numbered boxes. A secret rule turns each toy's name into a box number. To find a toy, you apply the rule and go straight to that box. You do not look through all the boxes.

How it works, step by step

  1. Make an array of buckets (shelves), all empty at the start.
  2. put(key, value): run the hash function on the key to get a bucket number, then store the pair in that bucket.
  3. get(key): run the same hash function, jump to that bucket, and return the value stored with that key.
  4. Because the hash function jumps straight to the bucket, the cost does not grow with the number of items (on average).
  5. Two keys can hash to the same bucket. That is a collision, and the next lessons show how to handle it. Our code keeps a small list inside each bucket.

The code in four languages

PHP

<?php
class HashTable {
    private array $buckets;
    public function __construct(private int $size = 7) {
        $this->buckets = array_fill(0, $size, []);   // each bucket is a small list of [key, value]
    }
    private function hash(string $key): int {
        $h = 0;
        for ($i = 0; $i < strlen($key); $i++) $h = ($h * 31 + ord($key[$i])) % $this->size;
        return $h;
    }
    public function put(string $key, $value): void {
        $b = $this->hash($key);
        foreach ($this->buckets[$b] as $i => $pair) {
            if ($pair[0] === $key) { $this->buckets[$b][$i][1] = $value; return; }   // update
        }
        $this->buckets[$b][] = [$key, $value];                                        // insert
    }
    public function get(string $key) {
        foreach ($this->buckets[$this->hash($key)] as [$k, $v]) {
            if ($k === $key) return $v;
        }
        return null;                                                                  // not found
    }
}

$t = new HashTable();
$t->put('Raju', 'chai');
$t->put('Mira', 'jalebi');
$t->put('Zoya', 'vada');
echo $t->get('Zoya') . "\n";                          // vada
echo $t->get('Mira') . "\n";                          // jalebi
$t->put('Mira', 'kachori');                            // update
echo $t->get('Mira') . "\n";                          // kachori
echo var_export($t->get('Kabir'), true) . "\n";       // NULL

JavaScript

class HashTable {
  constructor(size = 7) {
    this.size = size;
    this.buckets = Array.from({ length: size }, () => []);   // each bucket is a small list of [key, value]
  }
  hash(key) {
    let h = 0;
    for (let i = 0; i < key.length; i++) h = (h * 31 + key.charCodeAt(i)) % this.size;
    return h;
  }
  put(key, value) {
    const bucket = this.buckets[this.hash(key)];
    for (const pair of bucket) {
      if (pair[0] === key) { pair[1] = value; return; }      // update
    }
    bucket.push([key, value]);                               // insert
  }
  get(key) {
    for (const [k, v] of this.buckets[this.hash(key)]) {
      if (k === key) return v;
    }
    return null;                                             // not found
  }
}

const t = new HashTable();
t.put('Raju', 'chai');
t.put('Mira', 'jalebi');
t.put('Zoya', 'vada');
console.log(t.get('Zoya'));      // vada
console.log(t.get('Mira'));      // jalebi
t.put('Mira', 'kachori');        // update
console.log(t.get('Mira'));      // kachori
console.log(t.get('Kabir'));     // null

Java

import java.util.*;

public class Main {
    static class Entry {
        String key;
        String value;
        Entry(String key, String value) { this.key = key; this.value = value; }
    }

    static class HashTable {
        private final List<List<Entry>> buckets = new ArrayList<>();
        private final int size;

        HashTable(int size) {
            this.size = size;
            for (int i = 0; i < size; i++) buckets.add(new ArrayList<>());   // each bucket is a small list of key/value pairs
        }

        private int hash(String key) {
            int h = 0;
            for (int i = 0; i < key.length(); i++) h = (h * 31 + key.charAt(i)) % size;
            return h;
        }

        void put(String key, String value) {
            List<Entry> bucket = buckets.get(hash(key));
            for (Entry e : bucket) {
                if (e.key.equals(key)) { e.value = value; return; }   // update
            }
            bucket.add(new Entry(key, value));                        // insert
        }

        String get(String key) {
            for (Entry e : buckets.get(hash(key))) {
                if (e.key.equals(key)) return e.value;
            }
            return null;                                              // not found
        }
    }

    public static void main(String[] args) {
        HashTable t = new HashTable(7);
        t.put("Raju", "chai");
        t.put("Mira", "jalebi");
        t.put("Zoya", "vada");
        System.out.println(t.get("Zoya"));      // vada
        System.out.println(t.get("Mira"));      // jalebi
        t.put("Mira", "kachori");               // update
        System.out.println(t.get("Mira"));      // kachori
        System.out.println(t.get("Kabir"));     // null
    }
}

Go

package main

import "fmt"

type pair struct {
	key   string
	value string
}

type HashTable struct {
	buckets [][]pair // each bucket is a small list of key/value pairs
	size    int
}

func NewHashTable(size int) *HashTable {
	return &HashTable{buckets: make([][]pair, size), size: size}
}

func (t *HashTable) hash(key string) int {
	h := 0
	for i := 0; i < len(key); i++ {
		h = (h*31 + int(key[i])) % t.size
	}
	return h
}

func (t *HashTable) Put(key, value string) {
	b := t.hash(key)
	for i := range t.buckets[b] {
		if t.buckets[b][i].key == key {
			t.buckets[b][i].value = value // update
			return
		}
	}
	t.buckets[b] = append(t.buckets[b], pair{key, value}) // insert
}

func (t *HashTable) Get(key string) (string, bool) {
	for _, p := range t.buckets[t.hash(key)] {
		if p.key == key {
			return p.value, true
		}
	}
	return "", false // not found
}

func main() {
	t := NewHashTable(7)
	t.Put("Raju", "chai")
	t.Put("Mira", "jalebi")
	t.Put("Zoya", "vada")
	v, _ := t.Get("Zoya")
	fmt.Println(v) // vada
	v, _ = t.Get("Mira")
	fmt.Println(v)           // jalebi
	t.Put("Mira", "kachori") // update
	v, _ = t.Get("Mira")
	fmt.Println(v) // kachori
	if _, ok := t.Get("Kabir"); !ok {
		fmt.Println("null") // not found
	}
}

Time: O(1) average · Extra space: O(n). With a good hash function and enough buckets, each lookup jumps straight to a short bucket; in the worst case, all keys pile into one bucket and it becomes O(n).

Watch out for

  • Expecting a hash table to keep keys in sorted or insertion order. The buckets are arranged by hash, not by order.
  • Starting with far too few buckets so every bucket becomes a long list and lookups slow down.
  • Forgetting to compare the key itself inside the bucket: two different keys can share a shelf.

Quick check

  1. What does a hash table do to find the right shelf?
    • Searches every shelf
    • Applies the hash function to the key
    • Sorts the items first
  2. How fast is a typical lookup?
    • O(n)
    • O(log n)
    • O(1) on average
  3. Why store the key as well as the value in a bucket?
    • To tell apart different keys that share a bucket
    • To make the table look neat
    • To save memory