Algorithms

Hash table: how to find a value almost without searching

Cover of the article Hash table: how to find a value almost without searching
Focused reading

Understand the context.
Put it into practice.

Leia este artigo em português

In this article
  1. How does a hash table work?
  2. A hash function example, step by step
  3. What if two keys land in the same drawer?
  4. Hash table in PHP, Python, C and Java
  5. Why is a hash table so fast?
  6. Now you ask: have I used a hash table without knowing it?
  7. Now it’s your turn!

Hash table is a data structure that stores key-value pairs and uses a calculation made with the key to find out in which position the value should go. That’s why it finds a value without having to search item by item.

In the article on the binary tree, the challenge was to insert the values 45, 25, 65, 10 and 30. The answer: 45 is the root, 25 goes to its left and 65 to its right. 10 goes to the left of 25, and 30 to the right of 25. The leaves are 10, 30 and 65, and the in-order traversal shows 10, 25, 30, 45 and 65. Does it match your drawing?

How does a hash table work?

Think of a cabinet with numbered drawers in an office, with drawers from 0 to 7. To store someone’s card, you don’t pick the drawer by eye: you do a calculation with the person’s name, and the result tells you the drawer number. To find the card later, you just repeat the same calculation with the same name and go straight to the right drawer. Without opening the others!

Three-panel comic strip: in front of a cabinet with drawers from 0 to 7, a person does a calculation with the name Bruno, which gives 6, stores the card in drawer 6 and later repeats the calculation to find the card right away
The hash table as a cabinet of drawers: the calculation with the name says where to store and where to look.

This calculation is called a hash function. It takes the key and returns a number, which becomes the position inside an array.

  • Key: what you use to search. In our example, the person’s name.
  • Value: what gets stored. In our example, the phone extension.
  • Hash function: the calculation that turns the key into a position.

A hash function example, step by step

Let’s use a very simple function: add up the code of each letter in the key and take the remainder of the division by the number of drawers, which here is 8.

KeyLetter codesSumRemainder of the division by 8
Ana65 + 110 + 972720
Bruno66 + 114 + 117 + 110 + 1115186
Eva69 + 118 + 972844
The remainder of the division is the drawer number of each key.

So Ana goes to drawer 0, Bruno to drawer 6 and Eva to drawer 4. To look up Bruno’s extension, the program redoes the calculation, gets to 6, and that’s it!

What if two keys land in the same drawer?

It happens, and it has a name: collision. With our function, “Eva” and “Caio” give the same result: the sums 284 and 380 both leave a remainder of 4 when divided by 8. The two keys compete for drawer 4!

A very common solution is chaining: each drawer holds a small list. Whoever lands in the same drawer joins its list, and when searching, the program goes through only that little list, comparing the keys. Remember the linked list? There it is again!

Hash table diagram: the key Bruno goes through the hash function, which calculates drawer 6, in a table of eight drawers with a collision in drawer 4
From key to drawer: the hash function calculates the position, and two keys in the same drawer form a collision.
See the hash table animation, step by step
Animation of a hash table with eight drawers receiving the keys Ana, Bruno, Eva and Caio, with the collision in drawer 4 and the search for Bruno and for Caio
The calculation with the key points to the drawer. In a collision, the drawer becomes a small list.

Hash table in PHP, Python, C and Java

Here it is in PHP:

<?php

class HashTable
{
    private array $drawers;

    public function __construct(private int $size = 8)
    {
        $this->drawers = array_fill(0, $size, []);
    }

    private function hash(string $key): int
    {
        $sum = 0;

        foreach (str_split($key) as $letter) {
            $sum += ord($letter); // adds the code of each letter
        }

        return $sum % $this->size; // the remainder of the division becomes the position
    }

    public function put(string $key, string $value): void
    {
        $position = $this->hash($key);

        foreach ($this->drawers[$position] as $i => [$storedKey]) {
            if ($storedKey === $key) {
                $this->drawers[$position][$i] = [$key, $value]; // repeated key: replaces the value
                return;
            }
        }

        $this->drawers[$position][] = [$key, $value];
    }

    public function get(string $key): ?string
    {
        $position = $this->hash($key);

        foreach ($this->drawers[$position] as [$storedKey, $value]) {
            if ($storedKey === $key) {
                return $value;
            }
        }

        return null; // the key doesn't exist
    }
}

$extensions = new HashTable();
$extensions->put('Ana', '2101');
$extensions->put('Bruno', '2102');
$extensions->put('Eva', '2103');

echo $extensions->get('Bruno'), PHP_EOL; // 2102
echo $extensions->get('Eva'), PHP_EOL;   // 2103

In Python:

class HashTable:
    def __init__(self, size=8):
        self.size = size
        self.drawers = [[] for _ in range(size)]

    def _hash(self, key):
        total = 0

        for letter in key:
            total += ord(letter)  # adds the code of each letter

        return total % self.size  # the remainder of the division becomes the position

    def put(self, key, value):
        drawer = self.drawers[self._hash(key)]

        for item in drawer:
            if item[0] == key:
                item[1] = value  # repeated key: replaces the value
                return

        drawer.append([key, value])

    def get(self, key):
        drawer = self.drawers[self._hash(key)]

        for stored_key, value in drawer:
            if stored_key == key:
                return value

        return None  # the key doesn't exist


extensions = HashTable()
extensions.put("Ana", "2101")
extensions.put("Bruno", "2102")
extensions.put("Eva", "2103")

print(extensions.get("Bruno"))  # 2102
print(extensions.get("Eva"))    # 2103

And in C:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define SIZE 8

struct Item {
    const char *key;
    int value;
    struct Item *next;
};

struct Item *drawers[SIZE];

int hash(const char *key) {
    int sum = 0;

    for (int i = 0; key[i] != '\0'; i++) {
        sum += (unsigned char) key[i]; // adds the code of each letter
    }

    return sum % SIZE; // the remainder of the division becomes the position
}

void put(const char *key, int value) {
    int position = hash(key);

    for (struct Item *item = drawers[position]; item != NULL; item = item->next) {
        if (strcmp(item->key, key) == 0) {
            item->value = value; // repeated key: replaces the value
            return;
        }
    }

    struct Item *new_item = malloc(sizeof(struct Item));

    if (new_item == NULL) {
        return; // out of memory
    }

    new_item->key = key;
    new_item->value = value;
    new_item->next = drawers[position]; // joins the start of the drawer's list
    drawers[position] = new_item;
}

int get(const char *key) {
    for (struct Item *item = drawers[hash(key)]; item != NULL; item = item->next) {
        if (strcmp(item->key, key) == 0) {
            return item->value;
        }
    }

    return -1; // the key doesn't exist
}

int main(void) {
    put("Ana", 2101);
    put("Bruno", 2102);
    put("Eva", 2103);

    printf("%d\n", get("Bruno")); // 2102
    printf("%d\n", get("Eva"));   // 2103

    for (int i = 0; i < SIZE; i++) {
        while (drawers[i] != NULL) {
            struct Item *next = drawers[i]->next;
            free(drawers[i]); // in C, you give back the memory of each item
            drawers[i] = next;
        }
    }

    return 0;
}

And in Java:

import java.util.ArrayList;
import java.util.List;

public class HashTableByHand {
    static class HashTable {
        private final int size;
        private final List<List<String[]>> drawers = new ArrayList<>();

        HashTable(int size) {
            this.size = size;
            for (int i = 0; i < size; i++) {
                drawers.add(new ArrayList<>());
            }
        }

        private int hash(String key) {
            int sum = 0;
            for (char letter : key.toCharArray()) {
                sum += letter; // adds the code of each letter
            }
            return sum % size; // the remainder of the division becomes the position
        }

        void put(String key, String value) {
            List<String[]> drawer = drawers.get(hash(key));
            for (String[] item : drawer) {
                if (item[0].equals(key)) {
                    item[1] = value; // repeated key: replaces the value
                    return;
                }
            }
            drawer.add(new String[] {key, value});
        }

        String get(String key) {
            for (String[] item : drawers.get(hash(key))) {
                if (item[0].equals(key)) {
                    return item[1];
                }
            }
            return null; // the key doesn't exist
        }
    }

    public static void main(String[] args) {
        HashTable extensions = new HashTable(8);
        extensions.put("Ana", "2101");
        extensions.put("Bruno", "2102");
        extensions.put("Eva", "2103");
        System.out.println(extensions.get("Bruno")); // 2102
        System.out.println(extensions.get("Eva"));   // 2103
    }
}

Notice that put and get follow the same script: calculate the position with the hash function and look only at that drawer. And notice a detail in put: if the key already exists, the value is replaced, because in a hash table each key appears only once.

Why is a hash table so fast?

StructureHow it finds a valueComparisons in 1,000,000 items
Unsorted arrayLooks item by itemUp to 1,000,000
Sorted array, with binary searchCuts it in half at each stepUp to 20
Hash tableCalculates the position and goes straight thereA few, if the keys are well spread out
A comparison of the ways of searching we’ve seen so far.

IMPORTANT: this only holds when the hash function spreads the keys well. If they all land in the same drawer, the search turns into an item-by-item search inside it. The Python documentation gives the same warning about dictionaries: the operations are fast in the average case, and in the worst case, when every key results in the same hash, the time starts to grow along with the number of items.

And there’s a price: a hash table doesn’t keep the keys in order of size. If you need the values in ascending order, the binary search tree is the one for the job. Each structure has its moment!

Now you ask: have I used a hash table without knowing it?

Very likely! The PHP manual says the language’s arrays are actually ordered hash tables. And the Python dictionary also works with the hash of the keys. Here it is in PHP:

<?php

$extensions = ['Ana' => '2101', 'Bruno' => '2102'];
$extensions['Eva'] = '2103';

echo $extensions['Bruno'], PHP_EOL; // 2102

And in Python:

extensions = {"Ana": "2101", "Bruno": "2102"}
extensions["Eva"] = "2103"

print(extensions["Bruno"])  # 2102

And in Java, the ready-made class is HashMap, which the documentation describes as a hash table based implementation of a map:

import java.util.HashMap;
import java.util.Map;

public class HashMapExample {
    public static void main(String[] args) {
        Map<String, String> extensions = new HashMap<>();
        extensions.put("Ana", "2101");
        extensions.put("Bruno", "2102");
        extensions.put("Eva", "2103");
        System.out.println(extensions.get("Bruno")); // 2102
    }
}

Every time you write $extensions['Bruno'], what you just learned happens under the hood: a calculation with the key and a jump straight to the position. Who would have thought… Now you know what’s behind it!

Now it’s your turn!

On paper: which drawer does our hash function put the key Bia in? The letter codes are B = 66, i = 105 and a = 97. Does it collide with anyone from the example? Then check it in the code by printing the result of the hash function for “Bia”.

And a bigger challenge: create the remove method, which deletes a key from the table. Think before typing: which drawer should you look in? Try it on your own, without asking anyone for the ready-made answer. You can do it!

With the hash table, we close the data structures track: linked list, queue, binary tree and hash table. If you followed along and did the challenges, you already have a solid foundation to move forward. See you in the next article!

Stay confident!!!

Sources:

  • PHP Manual. SPL Datastructures, with the note that PHP arrays are in reality ordered hash tables.
  • PHP Manual. Arrays, with the array as an ordered map that can be treated as a hash table, a dictionary, a stack or a queue.
  • Python documentation. Time complexity of operations on built-in types, with the average-case times of dict and the worst case, when every key hashes to the same value.
  • Oracle, Java 21 documentation. HashMap class, a hash table based implementation of a map, with no order guarantee and constant time for get and put when the hash function spreads the elements well among the buckets.
  • Robert Sedgewick and Kevin Wayne, Princeton University. Algorithms, 3.4: Hash Tables, with modular hashing (the remainder of the division by the size of the array) and strings treated as numbers.
  • Princeton University, COS 226. Hash Tables, with separate chaining: an array of linked lists in which each new pair goes in at the front of its list (PDF).
  • Brad Miller and David Ranum, Problem Solving with Algorithms and Data Structures using Python. Hashing, with the hash function that adds up the ordinal values of the letters and takes the remainder by the table size.
  • Virginia Tech, CS 3114. Hash Functions, with the sum of the character codes taken modulo the table size, and the words that end up in the same position (PDF).
  • Virginia Tech. Hashing Tutorial: hash functions for strings, with the function that sums the codes of the letters and how well it spreads the keys depending on the table size.
  • University of Minnesota Duluth, CS 2511. Uniform Hashing, with keys turned into indexes by the remainder of the division and strings that have the same letters landing in the same position.
  • The examples were run on PHP 8.3, Python 3.13, GCC 13 and Java 21.

Share this article

About the author

Walmir Silva

Hi! I'm Walmir, a software engineer with an MBA in Software Engineering, the mind behind GrowthCode and the author of the book "Além do Código" (in Portuguese).

If you think programming is just about writing code, get ready to broaden your horizons. Here, we go beyond the code and explore the fascinating intersections between technology, business, the arts and philosophy.

Are you looking for career growth? Do you want to stand out in a competitive market? Are you after a life richer in knowledge and fulfillment? Then you've come to the right place. At GrowthCode, we offer deep insights, proven strategies and a touch of philosophical wisdom to fuel your personal and professional growth.

See all articles →

Continue the conversation

Share your perspective

Your email address will not be published. Required fields are marked *

We keep the IP address and browser of commenters for 6 months, to block spam and because Brazil’s Marco Civil da Internet requires access records to be kept for that period. See how we handle your data (in Portuguese).

Find your next answer

What do you want to learn?

Cookie preferences

Optional cookies start off. You can change your choice at any time on this screen.

NecessaryAlways on

They store your cookie choice and its record code, and keep the site working. They are not used for advertising.

They count visits and show how the site is used: Google Analytics and Microsoft Clarity, loaded by Google Tag Manager.

They show Google AdSense ads without personalization. The cookies in this category limit how often ads repeat and measure their results.

Uses your browsing to choose ads and build ad audiences: Google ads chosen by your interests and Google signals in Analytics. When off, ads are shown without personalization. Requires Advertising.

You can also block cookies in your browser settings. Details in the Privacy policy (in Portuguese).