Data structure · Hashing
Hash table
Keys hashed to buckets: expected O(1) insert, lookup and delete, as long as the hash spreads keys and the load factor stays bounded.
The derivations, edge cases and exercises are in the lesson Iterators, equality and hashing contracts. Open it full width in the playground.
On this page
The idea
A hash function turns a key into a bucket index. With separate chaining, each bucket holds the entries that landed there; a lookup hashes the key and scans one short chain.
The load factor (entries ÷ buckets) bounds the expected chain length. When it passes a threshold (0.75 in the teaching implementation), the table doubles its buckets and rehashes every entry, an O(n) step that amortizes to O(1) per insert.
Representation. An array of buckets, each a chain (list) of key–value entries.
Operations
| Operation | Time | Extra space | Notes |
|---|---|---|---|
| Put | O(1) expected, amortized | O(1) amortized | Worst case O(n) if every key collides. |
| Get | O(1) expected | O(1) | Worst case O(n). |
| Remove | O(1) expected | O(1) | Worst case O(n). |
| Iterate all entries | O(n + buckets) | O(1) | Order depends on the hash, not on insertion (except Python’s dict, which keeps insertion order). |
Invariants
What stays true before and after every operation.
- Every entry sits in bucket hash(key) mod capacity.
- Each key appears at most once in the whole table.
- size ÷ capacity stays at or below the maximum load factor after every put.
When to use it
Use it when
- You look up, count or deduplicate by key and do not need ordering.
- You trade O(n) memory for turning a nested-loop search into a single pass (complements, seen sets, frequency maps).
Avoid it when
- You need keys in sorted order or range queries (use a balanced search tree).
- Keys are mutable or their hash and equality disagree: entries become unreachable.
Built-in equivalents
What the standard library of each language offers. Linked types have a full page in the collections encyclopedia with every operation’s complexity, memory effects and a tested example.
C#
- Add / TryAdd O(1) including resizes
- Indexer this[TKey] O(1)
- TryGetValue O(1)
- ContainsKey / ContainsValue O(1) for ContainsKey
- Remove O(1)
- Add O(1)
- Contains O(1)
- Remove / RemoveWhere O(1) for Remove
- UnionWith / IntersectWith / ExceptWith O(m) for UnionWith and ExceptWith, where m is the size of other; IntersectWith O(n + m) in general
Python
- d[key] = value / setdefault O(1) including resizes
- d[key] O(1)
- get O(1)
- key in d O(1) for keys
- del d[key] / pop O(1)
- add O(1)
- elem in s O(1)
- remove / discard O(1)
- Set operators | & - ^ O(len(s) + len(t)) for union; O(min(len(s), len(t))) for intersection; O(len(s)) for difference
Java
- put / putIfAbsent O(1) including resizes
- get O(1)
- getOrDefault / merge O(1)
- containsKey / containsValue O(1) for containsKey
- remove O(1)
- add O(1)
- contains O(1)
- remove / removeIf O(1) for remove
- addAll / retainAll / removeAll addAll O(m); retainAll O(n) contains calls on c; removeAll depends on which side is smaller
C++
- insert / emplace / insert_or_assign O(1)
- operator[] / at O(1)
- find / contains / count O(1)
- erase O(1)
- insert / emplace O(1)
- contains / find / count O(1)
- erase / std::erase_if O(1) for erase(key)
- insert(first, last): union O(m) for m inserted elements
Step through it
The interactive lab for hash table: custom and seeded inputs, stepping forward and backward, with the active line highlighted in the code.
Implementation in four languages
The chained hash table in four languages, checked against one shared fixture of put, get and remove sequences, including collisions, overwrites and resizing.
namespace Bekadan.Dsa.Examples.Hashing;
/// <summary>
/// A teaching hash table with separate chaining. bucket = floorMod(key, capacity),
/// initial capacity 4, doubling before an insert would push the load factor
/// above 0.75. Dictionary<TKey, TValue> uses other details; the costs are the same.
/// </summary>
public sealed class ChainedHashTable
{
private List<(int Key, int Value)>[] _buckets = NewBuckets(4);
public int Count { get; private set; }
public int Capacity => _buckets.Length;
private static List<(int Key, int Value)>[] NewBuckets(int capacity)
{
var buckets = new List<(int Key, int Value)>[capacity];
for (int b = 0; b < capacity; b++)
buckets[b] = [];
return buckets;
}
private static int BucketOf(int key, int capacity) => ((key % capacity) + capacity) % capacity;
public void Put(int key, int value)
{
var chain = _buckets[BucketOf(key, _buckets.Length)];
for (int i = 0; i < chain.Count; i++)
{
if (chain[i].Key == key)
{
chain[i] = (key, value);
return;
}
}
if (4 * (Count + 1) > 3 * _buckets.Length) // (Count + 1) / capacity > 0.75, in integers
Resize();
_buckets[BucketOf(key, _buckets.Length)].Add((key, value));
Count++;
}
private void Resize()
{
var next = NewBuckets(_buckets.Length * 2);
foreach (var chain in _buckets)
foreach (var entry in chain)
next[BucketOf(entry.Key, next.Length)].Add(entry);
_buckets = next;
}
public bool TryGet(int key, out int value)
{
var chain = _buckets[BucketOf(key, _buckets.Length)];
foreach (var entry in chain)
{
if (entry.Key == key)
{
value = entry.Value;
return true;
}
}
value = 0;
return false;
}
public bool Remove(int key, out int value)
{
var chain = _buckets[BucketOf(key, _buckets.Length)];
for (int i = 0; i < chain.Count; i++)
{
if (chain[i].Key == key)
{
value = chain[i].Value;
chain.RemoveAt(i);
Count--;
return true;
}
}
value = 0;
return false;
}
}
Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Hashing/ChainedHashTable.cs
"""A teaching hash table with separate chaining.
bucket = key mod capacity (Python's % already floors for negative keys),
initial capacity 4, doubling before an insert would push the load factor
above 0.75. CPython's dict uses open addressing instead; the costs are the same.
"""
class ChainedHashTable:
def __init__(self) -> None:
self._buckets: list[list[tuple[int, int]]] = [[] for _ in range(4)]
self._count = 0
def __len__(self) -> int:
return self._count
@property
def capacity(self) -> int:
return len(self._buckets)
def put(self, key: int, value: int) -> None:
chain = self._buckets[key % len(self._buckets)]
for i, (existing, _) in enumerate(chain):
if existing == key:
chain[i] = (key, value)
return
if 4 * (self._count + 1) > 3 * len(self._buckets): # (count + 1) / capacity > 0.75, in integers
self._resize()
self._buckets[key % len(self._buckets)].append((key, value))
self._count += 1
def _resize(self) -> None:
new_buckets: list[list[tuple[int, int]]] = [[] for _ in range(2 * len(self._buckets))]
for chain in self._buckets:
for entry in chain:
new_buckets[entry[0] % len(new_buckets)].append(entry)
self._buckets = new_buckets
def get(self, key: int) -> int | None:
chain = self._buckets[key % len(self._buckets)]
for existing, value in chain:
if existing == key:
return value
return None
def remove(self, key: int) -> int | None:
chain = self._buckets[key % len(self._buckets)]
for i, (existing, value) in enumerate(chain):
if existing == key:
del chain[i]
self._count -= 1
return value
return None
Tested on CPython 3.14.0 · examples/python/dsa_examples/hash_table.py
package dev.bekadan.dsa.hashing;
import java.util.ArrayList;
import java.util.List;
import java.util.OptionalInt;
/**
* A teaching hash table with separate chaining. bucket = Math.floorMod(key, capacity),
* initial capacity 4, doubling before an insert would push the load factor above
* 0.75. HashMap uses other details (power-of-two tables, tree bins); the costs are the same.
*/
public final class ChainedHashTable {
private record Entry(int key, int value) {
}
private List<List<Entry>> buckets = newBuckets(4);
private int count;
private static List<List<Entry>> newBuckets(int capacity) {
List<List<Entry>> result = new ArrayList<>(capacity);
for (int b = 0; b < capacity; b++) {
result.add(new ArrayList<>());
}
return result;
}
public int size() {
return count;
}
public int capacity() {
return buckets.size();
}
public void put(int key, int value) {
List<Entry> chain = buckets.get(Math.floorMod(key, buckets.size()));
for (int i = 0; i < chain.size(); i++) {
if (chain.get(i).key() == key) {
chain.set(i, new Entry(key, value));
return;
}
}
if (4 * (count + 1) > 3 * buckets.size()) { // (count + 1) / capacity > 0.75, in integers
resize();
}
buckets.get(Math.floorMod(key, buckets.size())).add(new Entry(key, value));
count++;
}
private void resize() {
List<List<Entry>> next = newBuckets(buckets.size() * 2);
for (List<Entry> chain : buckets) {
for (Entry entry : chain) {
next.get(Math.floorMod(entry.key(), next.size())).add(entry);
}
}
buckets = next;
}
public OptionalInt get(int key) {
List<Entry> chain = buckets.get(Math.floorMod(key, buckets.size()));
for (Entry entry : chain) {
if (entry.key() == key) {
return OptionalInt.of(entry.value());
}
}
return OptionalInt.empty();
}
public OptionalInt remove(int key) {
List<Entry> chain = buckets.get(Math.floorMod(key, buckets.size()));
for (int i = 0; i < chain.size(); i++) {
if (chain.get(i).key() == key) {
int value = chain.remove(i).value();
count--;
return OptionalInt.of(value);
}
}
return OptionalInt.empty();
}
}
Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/hashing/ChainedHashTable.java
#pragma once
#include <cstddef>
#include <optional>
#include <utility>
#include <vector>
namespace bekadan::dsa {
// A teaching hash table with separate chaining. bucket = floorMod(key, capacity),
// initial capacity 4, doubling before an insert would push the load factor above
// 0.75. std::unordered_map uses other details (max_load_factor 1.0 by default).
class ChainedHashTable {
using Entry = std::pair<int, int>; // key, value
using Chain = std::vector<Entry>;
public:
[[nodiscard]] std::size_t size() const noexcept { return count_; }
[[nodiscard]] std::size_t capacity() const noexcept { return buckets_.size(); }
void put(int key, int value) {
Chain& chain = buckets_[bucket_of(key, buckets_.size())];
for (Entry& entry : chain) {
if (entry.first == key) {
entry.second = value;
return;
}
}
if (4 * (count_ + 1) > 3 * buckets_.size()) // (count + 1) / capacity > 0.75, in integers
resize(); // `chain` may dangle after this: look the bucket up again
buckets_[bucket_of(key, buckets_.size())].emplace_back(key, value);
++count_;
}
[[nodiscard]] std::optional<int> get(int key) const {
const Chain& chain = buckets_[bucket_of(key, buckets_.size())];
for (const Entry& entry : chain) {
if (entry.first == key)
return entry.second;
}
return std::nullopt;
}
std::optional<int> remove(int key) {
Chain& chain = buckets_[bucket_of(key, buckets_.size())];
for (std::size_t i = 0; i < chain.size(); ++i) {
if (chain[i].first == key) {
int value = chain[i].second;
chain.erase(chain.begin() + static_cast<std::ptrdiff_t>(i));
--count_;
return value;
}
}
return std::nullopt;
}
private:
static std::size_t bucket_of(int key, std::size_t capacity) {
const auto c = static_cast<long long>(capacity);
return static_cast<std::size_t>(((key % c) + c) % c);
}
void resize() {
std::vector<Chain> next(buckets_.size() * 2);
for (const Chain& chain : buckets_)
for (const Entry& entry : chain) next[bucket_of(entry.first, next.size())].push_back(entry);
buckets_ = std::move(next);
}
std::vector<Chain> buckets_ = std::vector<Chain>(4);
std::size_t count_ = 0;
};
} // namespace bekadan::dsa
Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/chained_hash_table.hpp
Learn more
Lessons
- Iterators, equality and hashing contracts· M04 Built-in Collections
- Hash tables: buckets, chaining and load factor· M10 Hash Tables and Sets
Problems, patterns and exercises
- PatternHashing for constant-time lookup· O(n) expected
- ProblemTwo readings that add up to a target· beginner · O(n) expected
- ProblemHas any badge been scanned twice?· beginner · O(n) expected
- ProblemSame letters, different order?· beginner · O(n) expected
- PatternPrefix sums· O(n) build, O(1) per query