Hash tables in Pascal
last modified November 19, 2026 Free Pascal 3.2.2
A hash table finds a value by computing its position from the key instead of searching through the data. The computation is a hash function, and the position is an array index. Different keys can land on the same index, which is a collision, so a real table also needs a rule for resolving collisions. This article builds the hash function first, shows a collision, resolves it with linear probing, adds lookup and values, and finally builds a table with separate chaining.
A hash function
A hash function turns a key into an integer in the range of the array. The one below uses a polynomial with base 31: it multiplies the running value by 31 and adds the next character code, then reduces modulo the table size. The modulo keeps the result inside the array, and the multiplier spreads similar strings apart.
program hash1;
{$mode objfpc}{$H+}
const
TableSize = 11;
function HashOf(const Key: string): Integer;
var
I: Integer;
begin
Result := 0;
for I := 1 to Length(Key) do
Result := (Result * 31 + Ord(Key[I])) mod TableSize;
end;
begin
WriteLn('Alice -> ', HashOf('Alice'));
WriteLn('Bob -> ', HashOf('Bob'));
WriteLn('Caroline -> ', HashOf('Caroline'));
WriteLn('Dan -> ', HashOf('Dan'));
end.
Alice and Caroline both hash to 4, so they cannot
both occupy slot 4. That is a collision, and it is normal: eleven slots cannot
give every string a unique index. The hash is deterministic, so the same key
always produces the same index, which is what makes lookup possible.
$ fpc -gl hash1.pas $ ./hash1 Alice -> 4 Bob -> 8 Caroline -> 4 Dan -> 1
A unit for the hash function
Every program in the rest of this article needs the same hash function, so it
goes into a unit. The table size becomes a
parameter, because the last example uses a smaller table than the others. A
program that names hashfn in its uses clause gets
HashOf, and the compiler builds the unit automatically when it
compiles the program.
unit hashfn;
{$mode objfpc}{$H+}
interface
function HashOf(const Key: string; Size: Integer): Integer;
implementation
function HashOf(const Key: string; Size: Integer): Integer;
var
I: Integer;
begin
Result := 0;
for I := 1 to Length(Key) do
Result := (Result * 31 + Ord(Key[I])) mod Size;
end;
end.
The unit has no main block. Its interface section declares the
function and its implementation section holds the body, which is
the polynomial hash from the previous example.
Collisions
The most direct table stores each key in the slot that its hash selects. The program below does exactly that with an array of eleven strings. An empty string marks a free slot.
program collide;
{$mode objfpc}{$H+}
uses hashfn;
const
TableSize = 11;
var
Slots: array[0..TableSize - 1] of string;
I: Integer;
begin
Slots[HashOf('Alice', TableSize)] := 'Alice';
Slots[HashOf('Bob', TableSize)] := 'Bob';
Slots[HashOf('Caroline', TableSize)] := 'Caroline';
Slots[HashOf('Dan', TableSize)] := 'Dan';
for I := 0 to TableSize - 1 do
if Slots[I] <> '' then
WriteLn(I, ': ', Slots[I]);
end.
Only three names are printed although four were stored. Alice and
Caroline share slot 4, so the second assignment overwrote the
first. Every hash table needs a rule for this case; the next two sections use
linear probing and the last one uses separate chaining.
$ fpc -gl collide.pas $ ./collide 1: Dan 4: Caroline 8: Bob
Linear probing
Linear probing keeps all keys in the array. When the home slot is taken by a
different key, Put tries the next slot, and the one after that,
wrapping around at the end of the array. Each slot gets a Used
flag, because the empty string is a valid key and cannot mark a free slot.
program probe;
{$mode objfpc}{$H+}
uses hashfn;
const
TableSize = 11;
type
TSlot = record
Key: string;
Used: Boolean;
end;
var
Slots: array[0..TableSize - 1] of TSlot;
procedure Put(const Key: string);
var
Index: Integer;
begin
Index := HashOf(Key, TableSize);
while Slots[Index].Used and (Slots[Index].Key <> Key) do
Index := (Index + 1) mod TableSize;
Slots[Index].Key := Key;
Slots[Index].Used := True;
end;
var
I: Integer;
begin
for I := 0 to TableSize - 1 do
Slots[I].Used := False;
Put('Alice');
Put('Bob');
Put('Caroline');
Put('Dan');
Put('Alice');
for I := 0 to TableSize - 1 do
if Slots[I].Used then
WriteLn(I, ': ', Slots[I].Key);
end.
The while loop stops at a free slot or at the slot that already
holds the key. Caroline finds slot 4 occupied by
Alice and moves on to slot 5. The second Put('Alice')
stops at slot 4, so a key is never stored twice. The loop assumes that the
table always has a free slot; a full table would make it run forever, which is
why real tables grow before they fill up.
$ fpc -gl probe.pas $ ./probe 1: Dan 4: Alice 5: Caroline 8: Bob
Looking up a key
A lookup follows the same probe sequence as the insertion. It starts at the home slot and moves forward until it finds the key or reaches a free slot.
program lookup;
{$mode objfpc}{$H+}
uses hashfn;
const
TableSize = 11;
type
TSlot = record
Key: string;
Used: Boolean;
end;
var
Slots: array[0..TableSize - 1] of TSlot;
procedure Put(const Key: string);
var
Index: Integer;
begin
Index := HashOf(Key, TableSize);
while Slots[Index].Used and (Slots[Index].Key <> Key) do
Index := (Index + 1) mod TableSize;
Slots[Index].Key := Key;
Slots[Index].Used := True;
end;
function Contains(const Key: string): Boolean;
var
Index: Integer;
begin
Index := HashOf(Key, TableSize);
while Slots[Index].Used do
begin
if Slots[Index].Key = Key then
Exit(True);
Index := (Index + 1) mod TableSize;
end;
Result := False;
end;
var
I: Integer;
begin
for I := 0 to TableSize - 1 do
Slots[I].Used := False;
Put('Alice');
Put('Bob');
Put('Caroline');
WriteLn('Alice: ', Contains('Alice'));
WriteLn('Caroline: ', Contains('Caroline'));
WriteLn('Xavier: ', Contains('Xavier'));
end.
A free slot ends the search, because Put would have stored the key
there if it had not been found earlier in the sequence. A lookup for
Caroline visits slots 4 and 5; a lookup for Xavier
stops at the first unused slot and returns False.
$ fpc -gl lookup.pas $ ./lookup Alice: TRUE Caroline: TRUE Xavier: FALSE
Storing values
A map stores a value with every key. Insertion and lookup now walk the same
probe sequence, so the walk moves into a helper function,
FindSlot, which returns either the slot that holds the key or the
free slot where the key belongs.
program scores;
{$mode objfpc}{$H+}
uses hashfn;
const
TableSize = 11;
type
TSlot = record
Key: string;
Value: Integer;
Used: Boolean;
end;
var
Slots: array[0..TableSize - 1] of TSlot;
function FindSlot(const Key: string): Integer;
begin
Result := HashOf(Key, TableSize);
while Slots[Result].Used and (Slots[Result].Key <> Key) do
Result := (Result + 1) mod TableSize;
end;
procedure Put(const Key: string; Value: Integer);
var
Index: Integer;
begin
Index := FindSlot(Key);
Slots[Index].Key := Key;
Slots[Index].Value := Value;
Slots[Index].Used := True;
end;
function Get(const Key: string; out Value: Integer): Boolean;
var
Index: Integer;
begin
Index := FindSlot(Key);
Result := Slots[Index].Used;
if Result then
Value := Slots[Index].Value;
end;
var
I, Score: Integer;
begin
for I := 0 to TableSize - 1 do
Slots[I].Used := False;
Put('Alice', 92);
Put('Bob', 78);
Put('Caroline', 85);
Put('Alice', 95);
if Get('Alice', Score) then WriteLn('Alice = ', Score);
if Get('Caroline', Score) then WriteLn('Caroline = ', Score);
if not Get('Xavier', Score) then WriteLn('Xavier not found');
end.
Put writes the key and the value into the slot that
FindSlot returns, so writing an existing key replaces its value:
Alice ends with 95, not 92. Get reports whether the
slot is in use and returns the value through an out parameter.
$ fpc -gl scores.pas $ ./scores Alice = 95 Caroline = 85 Xavier not found
Separate chaining
Separate chaining resolves collisions outside the array. Every slot is the head of a linked list, and keys that hash to the same slot share its list. The table can hold more entries than slots, but a long chain turns a lookup into a linear search. This version uses seven buckets.
program chaining;
{$mode objfpc}{$H+}
uses hashfn;
const
TableSize = 7;
type
PEntry = ^TEntry;
TEntry = record
Key: string;
Value: Integer;
Next: PEntry;
end;
var
Buckets: array[0..TableSize - 1] of PEntry;
function Find(const Key: string): PEntry;
begin
Result := Buckets[HashOf(Key, TableSize)];
while (Result <> nil) and (Result^.Key <> Key) do
Result := Result^.Next;
end;
procedure Put(const Key: string; Value: Integer);
var
Entry: PEntry;
Index: Integer;
begin
Entry := Find(Key);
if Entry = nil then
begin
Index := HashOf(Key, TableSize);
New(Entry);
Entry^.Key := Key;
Entry^.Next := Buckets[Index];
Buckets[Index] := Entry;
end;
Entry^.Value := Value;
end;
procedure FreeBuckets;
var
I: Integer;
Next: PEntry;
begin
for I := 0 to TableSize - 1 do
while Buckets[I] <> nil do
begin
Next := Buckets[I]^.Next;
Dispose(Buckets[I]);
Buckets[I] := Next;
end;
end;
var
I: Integer;
Entry: PEntry;
begin
for I := 0 to TableSize - 1 do
Buckets[I] := nil;
Put('Alice', 92);
Put('Bob', 78);
Put('Caroline', 85);
Put('Dan', 60);
Put('Alice', 95);
for I := 0 to TableSize - 1 do
begin
Write(I, ':');
Entry := Buckets[I];
while Entry <> nil do
begin
Write(' ', Entry^.Key, '=', Entry^.Value);
Entry := Entry^.Next;
end;
WriteLn;
end;
FreeBuckets;
end.
Find walks one chain and returns the entry or nil.
Put updates an entry that exists and otherwise prepends a new one
to its bucket, which takes constant time. The main block prints every bucket:
Alice and Caroline share bucket 4, and
Caroline comes first because it was prepended later.
FreeBuckets disposes every entry before the program ends.
$ fpc -gl chaining.pas $ ./chaining 0: 1: 2: 3: Bob=78 4: Caroline=85 Alice=95 5: Dan=60 6:
Load factor and deletion
The load factor is the number of entries divided by the number of slots. A low load factor keeps probes and chains short; as the table fills, collisions become more frequent and the constant-time promise weakens. A production table resizes when the load factor crosses a threshold, usually around 0.7, and reinserts the entries into a larger array. The examples here use fixed sizes to keep the code short.
Deletion in open addressing is harder than insertion. Clearing a slot would break the probe sequence of keys that were placed after it, so the slot must be marked as deleted and skipped during lookup but reused during insertion. Separate chaining avoids the problem because removing a node only changes the links in one chain.
Next steps
The searching article compares these lookups
with linear and binary search, and the
generics article explains the
TDictionary that hides the same structure behind an interface. The
linked lists article explains the nodes used
by chaining, and the binary trees article
offers a third structure for ordered lookup.
Source
In this article we hashed strings into array indices, moved the hash function into a unit, watched a collision overwrite a key, resolved collisions with linear probing, added lookup and values, and built a table with separate chaining. The series continues with procedural types and callbacks in Pascal.
Author
List all Pascal tutorials.