AlgoTales · Roadmap

Open addressing

Advanced · 11 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Open addressing is a collision rule where every item lives directly in the table slot itself, with no extra lists. If your slot is taken, you step to the next free one by a fixed pattern. It is compact and friendly to the computer memory.

Practical use cases

  • Web app: Fast in-memory counter for page views. An analytics endpoint counts hits per page id thousands of times a second. A flat table with no extra lists keeps everything packed together, so the processor reads it quickly. When two pages collide, the second just takes the next free seat, and counting stays smooth under heavy traffic.
  • Web app: Unique visitors set. A dashboard needs to know whether a visitor id has already been counted today. Each id is placed in a flat table; if the slot is busy, the code probes the next one. Checking "seen before?" takes a few neighbouring slots rather than a long search through a list.
  • System: Python dict and set. Python dictionaries and sets use this approach: items sit in one array and collisions move to another slot in the same array. Deleted items leave a small marker so searches do not stop too early, which is why such tables occasionally rebuild themselves.

The story: The Parking Lot With No Rules

Outside Ravi's cricket ground there was a parking lot with seven numbered spots and a very simple rule: your scooter's number plate told you your spot. Raju's plate said spot 1. Bhaskar's plate also said spot 1. Awkward!

The guard, Dhanraj, made a rule that never needed a second parking area: if your spot is taken, take the next one, and the next, wrapping round at the end of the row. So Bhaskar parked at spot 2, Kabir (whose plate said 2) at spot 3, and Aarav at spot 4. To find Aarav's scooter you start at spot 2, and walk forward until you find it or hit a truly empty spot.

One day Bhaskar left, and Dhanraj cleared spot 2. Then Mira came asking for Kabir's scooter. She went to spot 2, found it empty, and said "not here". Wrong! Kabir was one spot further. Dhanraj learned a lesson: when someone leaves, put a cone (a tombstone) on the spot instead of leaving it empty, so searchers keep walking. This parking rule is open addressing with linear probing.

How to spot this problem, and where you need it

You need a very fast lookup table that uses little memory and avoids creating many small objects, and you can keep the table mostly empty.

Signs you need it

  • Memory or speed matters: the table sits in a hot path, runs on a small device, or is hit millions of times.
  • You know roughly how many items will arrive, so you can reserve space with plenty of empty slots.
  • The problem says "linear probing", "probe sequence", "tombstone" or "no extra data structures per slot".
  • A table full of tiny linked lists causes too many allocations and your profile shows time lost jumping around memory.

Where to use it in a project

  • Counters, visited-id sets or caches inside a performance-critical background job or an embedded device.
  • Understanding why a Python dict or JS object slows down and rebuilds when it becomes crowded.

The solution

Keep one array and leave a good part of it empty. To insert, go to the hashed slot; if it is taken, check the next slot, and the next, until you find an empty one. To search, follow the same walk and stop at an empty slot. When removing, leave a marker instead of an empty hole so later searches continue past it. Grow and re-insert everything when the table gets about two-thirds full.

Payoff: Before: thousands of small list objects and scattered memory. After: one flat array with lookups in about 1 to 3 probes.

Explain it like I am 8

A row of numbered seats, and each kid has a favourite seat number. If your seat is taken, you sit in the next free one. When someone leaves, we put a small flag on that seat so that people looking for friends know to keep going.

How it works, step by step

  1. Keep one flat array of slots (each empty, taken, or marked with a tombstone).
  2. put(key): hash to slot i. While slot i is taken by another key, move to (i + 1) % size. Place the key in the first free (or tombstone) slot.
  3. get(key): start at the hashed slot and walk forward. Stop with "found" if the key matches, or with "not here" when you reach a truly empty slot. Tombstones are stepped over.
  4. remove(key): find the key as in get, but replace it with a tombstone, never with empty.
  5. Keep the table less than about two-thirds full, otherwise probe paths get long. If full, grow and re-hash.

The code in four languages

PHP

<?php
class ProbingMap {
    private array $keys, $vals;
    // null = empty slot, false = tombstone (a deleted key), string = a stored key
    public function __construct(private int $cap = 7) {
        $this->keys = array_fill(0, $cap, null);
        $this->vals = array_fill(0, $cap, null);
    }
    private function hash(string $key): int {
        $h = 0;
        for ($i = 0; $i < strlen($key); $i++) $h = ($h * 31 + ord($key[$i])) % $this->cap;
        return $h;
    }
    public function put(string $key, $value): bool {
        $i = $this->hash($key);
        $firstFree = -1;
        for ($n = 0; $n < $this->cap; $n++, $i = ($i + 1) % $this->cap) {
            if ($this->keys[$i] === $key) { $this->vals[$i] = $value; return true; }   // update
            if ($this->keys[$i] === false && $firstFree < 0) $firstFree = $i;          // remember a tombstone
            if ($this->keys[$i] === null) { if ($firstFree < 0) $firstFree = $i; break; }
        }
        if ($firstFree < 0) return false;                                              // table full
        $this->keys[$firstFree] = $key;
        $this->vals[$firstFree] = $value;
        return true;
    }
    public function get(string $key) {
        $i = $this->hash($key);
        for ($n = 0; $n < $this->cap; $n++, $i = ($i + 1) % $this->cap) {
            if ($this->keys[$i] === null) return null;        // truly empty: not here
            if ($this->keys[$i] === $key) return $this->vals[$i];
        }                                                      // tombstones: keep walking
        return null;
    }
    public function remove(string $key): bool {
        $i = $this->hash($key);
        for ($n = 0; $n < $this->cap; $n++, $i = ($i + 1) % $this->cap) {
            if ($this->keys[$i] === null) return false;
            if ($this->keys[$i] === $key) { $this->keys[$i] = false; $this->vals[$i] = null; return true; }
        }
        return false;
    }
}

$m = new ProbingMap(7);
foreach (['Raju', 'Bhaskar', 'Kabir', 'Aarav'] as $i => $k) $m->put($k, $i + 1);
echo $m->get('Aarav') . "\n";                          // 4 (found after probing)
$m->remove('Bhaskar');                                  // leaves a tombstone
echo $m->get('Kabir') . "\n";                          // 3 (still found past the tombstone)
echo var_export($m->get('Bhaskar'), true) . "\n";      // NULL

JavaScript

const TOMB = Symbol('tombstone');   // marks a deleted slot; null means truly empty

class ProbingMap {
  constructor(cap = 7) {
    this.cap = cap;
    this.keys = new Array(cap).fill(null);
    this.vals = new Array(cap).fill(null);
  }
  hash(key) {
    let h = 0;
    for (let i = 0; i < key.length; i++) h = (h * 31 + key.charCodeAt(i)) % this.cap;
    return h;
  }
  put(key, value) {
    let i = this.hash(key), firstFree = -1;
    for (let n = 0; n < this.cap; n++, i = (i + 1) % this.cap) {
      if (this.keys[i] === key) { this.vals[i] = value; return true; }      // update
      if (this.keys[i] === TOMB && firstFree < 0) firstFree = i;            // remember a tombstone
      if (this.keys[i] === null) { if (firstFree < 0) firstFree = i; break; }
    }
    if (firstFree < 0) return false;                                        // table full
    this.keys[firstFree] = key;
    this.vals[firstFree] = value;
    return true;
  }
  get(key) {
    let i = this.hash(key);
    for (let n = 0; n < this.cap; n++, i = (i + 1) % this.cap) {
      if (this.keys[i] === null) return null;          // truly empty: not here
      if (this.keys[i] === key) return this.vals[i];
    }                                                  // tombstones: keep walking
    return null;
  }
  remove(key) {
    let i = this.hash(key);
    for (let n = 0; n < this.cap; n++, i = (i + 1) % this.cap) {
      if (this.keys[i] === null) return false;
      if (this.keys[i] === key) { this.keys[i] = TOMB; this.vals[i] = null; return true; }
    }
    return false;
  }
}

const m = new ProbingMap(7);
['Raju', 'Bhaskar', 'Kabir', 'Aarav'].forEach((k, i) => m.put(k, i + 1));
console.log(m.get('Aarav'));      // 4 (found after probing)
m.remove('Bhaskar');              // leaves a tombstone
console.log(m.get('Kabir'));      // 3 (still found past the tombstone)
console.log(m.get('Bhaskar'));    // null

Java

import java.util.*;

public class Main {
    static class ProbingMap {
        // A slot is empty (null, never used), TOMB (a deleted key) or holds a stored key.
        private static final String TOMB = new String("<tombstone>");   // unique object, compared with ==
        private final String[] keys;
        private final Integer[] vals;
        private final int cap;

        ProbingMap(int cap) {
            this.cap = cap;
            keys = new String[cap];
            vals = new Integer[cap];
        }

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

        boolean put(String key, int value) {
            int i = hash(key), firstFree = -1;
            for (int n = 0; n < cap; n++, i = (i + 1) % cap) {
                if (keys[i] != null && keys[i] != TOMB && keys[i].equals(key)) { vals[i] = value; return true; }   // update
                if (keys[i] == TOMB && firstFree < 0) firstFree = i;       // remember a tombstone
                if (keys[i] == null) { if (firstFree < 0) firstFree = i; break; }
            }
            if (firstFree < 0) return false;                               // table full
            keys[firstFree] = key;
            vals[firstFree] = value;
            return true;
        }

        Integer get(String key) {
            int i = hash(key);
            for (int n = 0; n < cap; n++, i = (i + 1) % cap) {
                if (keys[i] == null) return null;                          // truly empty: not here
                if (keys[i] != TOMB && keys[i].equals(key)) return vals[i];
            }                                                              // tombstones: keep walking
            return null;
        }

        boolean remove(String key) {
            int i = hash(key);
            for (int n = 0; n < cap; n++, i = (i + 1) % cap) {
                if (keys[i] == null) return false;
                if (keys[i] != TOMB && keys[i].equals(key)) { keys[i] = TOMB; vals[i] = null; return true; }
            }
            return false;
        }
    }

    public static void main(String[] args) {
        ProbingMap m = new ProbingMap(7);
        String[] names = {"Raju", "Bhaskar", "Kabir", "Aarav"};
        for (int i = 0; i < names.length; i++) m.put(names[i], i + 1);
        System.out.println(m.get("Aarav"));      // 4 (found after probing)
        m.remove("Bhaskar");                     // leaves a tombstone
        System.out.println(m.get("Kabir"));      // 3 (still found past the tombstone)
        System.out.println(m.get("Bhaskar"));    // null
    }
}

Go

package main

import "fmt"

// Each slot is empty (never used), a tombstone (a deleted key) or holds a key.
type state int

const (
	empty state = iota
	tomb
	full
)

type slot struct {
	state state
	key   string
	val   int
}

type ProbingMap struct {
	slots []slot
}

func NewProbingMap(capacity int) *ProbingMap {
	return &ProbingMap{slots: make([]slot, capacity)}
}

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

func (m *ProbingMap) Put(key string, value int) bool {
	capacity := len(m.slots)
	i, firstFree := m.hash(key), -1
	for n := 0; n < capacity; n, i = n+1, (i+1)%capacity {
		s := m.slots[i]
		if s.state == full && s.key == key {
			m.slots[i].val = value // update
			return true
		}
		if s.state == tomb && firstFree < 0 {
			firstFree = i // remember a tombstone
		}
		if s.state == empty {
			if firstFree < 0 {
				firstFree = i
			}
			break
		}
	}
	if firstFree < 0 {
		return false // table full
	}
	m.slots[firstFree] = slot{full, key, value}
	return true
}

func (m *ProbingMap) Get(key string) (int, bool) {
	capacity := len(m.slots)
	i := m.hash(key)
	for n := 0; n < capacity; n, i = n+1, (i+1)%capacity {
		s := m.slots[i]
		if s.state == empty {
			return 0, false // truly empty: not here
		}
		if s.state == full && s.key == key {
			return s.val, true
		}
	} // tombstones: keep walking
	return 0, false
}

func (m *ProbingMap) Remove(key string) bool {
	capacity := len(m.slots)
	i := m.hash(key)
	for n := 0; n < capacity; n, i = n+1, (i+1)%capacity {
		s := m.slots[i]
		if s.state == empty {
			return false
		}
		if s.state == full && s.key == key {
			m.slots[i] = slot{state: tomb}
			return true
		}
	}
	return false
}

func main() {
	m := NewProbingMap(7)
	for i, k := range []string{"Raju", "Bhaskar", "Kabir", "Aarav"} {
		m.Put(k, i+1)
	}
	v, _ := m.Get("Aarav")
	fmt.Println(v)      // 4 (found after probing)
	m.Remove("Bhaskar") // leaves a tombstone
	v, _ = m.Get("Kabir")
	fmt.Println(v) // 3 (still found past the tombstone)
	if _, ok := m.Get("Bhaskar"); !ok {
		fmt.Println("null")
	}
}

Time: O(1) average, O(n) worst · Extra space: O(n). While the table has plenty of free slots probe paths are short; as it fills up, searches walk further, so keep it well below full.

Watch out for

  • Marking a deleted slot as empty instead of a tombstone, which breaks searches for keys that were placed after a collision.
  • Letting the table fill up completely: a lookup for a missing key would loop forever without a cap on the number of probes.
  • Forgetting to wrap around with % size when the probe reaches the last slot.

Quick check

  1. In linear probing, what do you do when the hashed slot is taken?
    • Overwrite it
    • Check the next slot (wrapping around)
    • Throw an error
  2. Why do we leave a tombstone when removing?
    • So searches do not stop early at a slot that used to be occupied
    • To save time
    • To keep the table sorted
  3. A search stops with "not found" when it reaches...
    • A tombstone
    • A slot with a different key
    • A truly empty slot