Quadratic Probing in C++: Complete Guide with Code Examples
Quadratic probing in C++ is a collision resolution strategy for open-addressing hash tables. When two keys map to the same bucket, the table does not create a linked list; it probes a sequence of alternative slots using quadratic offsets. This makes the data structure compact, cache-friendly, and often faster than separate chaining for small to medium-sized tables.
If you have ever watched a hash table slow down as it fills up, the probing method is usually part of the story. Quadratic probing reduces the primary clustering that plagues linear probing, but it also demands careful attention to table size, load factor, and deletion. A correct C++ implementation must respect those constraints, or it can fail to find empty slots even when space remains.
How Quadratic Probing Works in C++
At its core, quadratic probing starts with a hash value and then checks slots at increasing quadratic offsets. A typical sequence is the initial bucket, then the bucket one squared positions away, then two squared, then three squared, wrapping around with modulo arithmetic. The capacity determines how the sequence wraps and whether it can visit every bucket.
In C++, the hash value might come from std::hash or a custom hash functor. The table stores buckets in a contiguous array, often std::vector, and each probe is just an index calculation. That simplicity is appealing, but the mathematical behavior of the probe sequence is what separates a reliable table from a buggy one.
The Core Formula and Probing Sequence
The common quadratic probing formula is index = (hash(key) + i squared) % capacity, where i starts at zero and increases after every collision. The first probe checks the initial hash, the second checks one slot beyond it, the third checks four slots beyond it, and so on. This growing step size spreads keys away from their original cluster more aggressively than linear probing.
For example, with capacity 11 and an initial hash of 7, the sequence becomes 7, 8, 0, 5, 1, and so on as you continue squaring and taking the modulo. The gaps grow as 1, 3, 5, 7, which helps avoid long contiguous runs of occupied slots. However, the sequence is not guaranteed to cover every slot unless the capacity is chosen correctly, which is why prime table sizes are common in C++ implementations.
Why Table Size and Load Factor Matter
Table size is not an arbitrary detail in quadratic probing. With the simple formula above, a power-of-two capacity can restrict the probe sequence to only a fraction of the table, causing insertion failures even when the table is not full. Prime capacities are often used because they allow the sequence to visit more slots and reduce the chance of an incomplete probe path.
The load factor, calculated as stored elements divided by capacity, controls how often collisions happen. Quadratic probing performs best when the load factor stays below roughly 0.5. Once the table becomes too crowded, the average probe length rises quickly, and operations can approach linear time. In C++, a resize that doubles the capacity and rehashes every key is the usual remedy, but the new capacity should still satisfy the prime or coverage requirements.
Implementing Quadratic Probing in C++
A practical C++ implementation combines a bucket array with a way to distinguish empty, occupied, and deleted slots. The bucket array might be a std::vector of key-value nodes, while a separate state array or sentinel values track the condition of each slot. The hash function and equality comparator are supplied by the table or by template parameters, similar to how std::unordered_map works.
Insertion, search, and deletion all follow the same probe sequence, but they interpret slot states differently. Insertion can reuse a deleted slot, search must continue past deleted slots, and deletion must leave a tombstone instead of clearing the slot outright. Resizing is also part of the implementation: when the load factor crosses a threshold, allocate a larger table and reinsert every occupied element. These details are where most performance and correctness issues appear.
Building the Hash Table Class and Insertion Logic
A simple C++ class might store an array of optional-like entries and a size counter. The insert method computes the initial hash, then loops from i equals zero to capacity minus one. At each step, it calculates the quadratic index, checks whether the slot is empty, occupied, or deleted, and either updates an existing key, claims an empty or deleted slot, or continues probing. If the loop finishes without finding a slot, the table needs to resize or report that it is full.
When inserting, remember the first deleted slot you encounter but keep probing in case the key already exists later in the sequence. If you stop at the first tombstone and insert immediately, you may create duplicate keys. When an empty slot is reached before finding the key, the key is not present, and the saved tombstone can be reused. This approach keeps insertion efficient while preserving the integrity of the probe chain.
Search, Deletion, and Tombstone Handling
Searching uses the same sequence as insertion. At each probed index, an empty slot means the key is absent because insertion would have placed it before that empty slot. An occupied slot with a matching key means success. An occupied slot with a different key or a deleted slot means keep probing. The loop must be bounded by the capacity to avoid infinite scans when the table is full or the probe sequence is incomplete.
Deletion is the step that trips up many hand-written C++ hash tables. You cannot simply mark a slot as empty, because another key may have been inserted after a collision and its probe path may pass through that slot. Instead, mark the slot as deleted, often called a tombstone. Tombstones can be reused by later insertions, but they must be counted when deciding to rehash, because too many tombstones increase probe lengths and waste memory.
A well-tuned quadratic probing table can be an excellent alternative to std::unordered_map when memory locality and compact storage matter. Start with a prime capacity, keep the load factor low, handle tombstones carefully, and benchmark against your real workload before committing to it. With those habits, you can build a C++ hash table that stays fast under pressure and behaves predictably when the data grows.