Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Hash table

Hash table

A hash table (Hash Table), also called a hash map, is an efficient data structure that accesses values (Value) directly by key (Key).

On average it only needs time complexity close to O(1) to complete the insertion, deletion, and lookup of data.

By comparison, searching by value in an array is O(n), and in a balanced binary search tree it is O(log n), and the larger the data set, the more obvious the advantage of the hash table.

Operation Array / Linked List Hash Table (average)
Search by value O(n) O(1)
Insertion (including location) O(n) O(1)
Deletion (including location) O(n) O(1)
Space utilization High Medium

in the table O(1) IsAverage Case。

When hash collisions are very severe, a single operation can degrade in the worst case to O(n)a much higher complexity; the "load factor" section later will explain how to avoid this.

A hash table is like a smart locker system.

Traditional lockers have no index, so you must remember which locker each item is in, and finding things means searching locker by locker.

A smart locker is different: you tell the administrator the item's name, he directly reports the locker number, and you walk to the corresponding location to retrieve the item.

There are many similar scenarios in daily life:

Real-life scenario Hashing idea reflected
Looking up a word in a dictionary quickly locate the page by the word's first letter
Telephone directory sorted by the pinyin of surnames, quickly find a contact
Library call number directly locate the shelf position by the classification number

Imagine a library with tens of thousands of books, and you want to find Harry Potter.

The dumbest way is to start from the first book on the first shelf and flip through them one by one, which might take hours.

A smart librarian would use anindex system: using some rule based on the title or author (such as the first letter), first locate a broad area, then search within a smaller range.

The idea of this index system is exactly the core of a hash table.


Basic concepts

Before learning the implementation, first understand the components and workflow of a hash table.

What is a hash table?

A hash table is a data structure that accesses values (Value) directly by key (Key).

It uses a conversion rule called ahash functionto convert keys of any size (strings, numbers, or objects) into a number within a fixed range; this number is called ahash value。

The hash value is then used as the index of the underlying arrayIndex, and the value is stored at the array position corresponding to that index.

This is like assigning a unique seat number to each key: when you want to find data, you recalculate the seat number using the same rule, walk straight over and get it, without asking seat by seat.

Core Components

A hash table mainly consists of three parts; take the telephone directory as an example:

Component Purpose Corresponding item in the telephone directory
Key the identifier used when storing and searching for data Person's name
Value the actual data associated with the key Phone number
Hash Function maps keys to array indices; it is the heart of the hash table the rule for ordering pages by the pinyin of surnames

How it works, illustrated

Suppose we want to create a telephone directory that maps people's names to phone numbers.

The figure above shows the workflow of a hash table: whether inserting or searching, it all starts with a key.

The key first goes through the hash function to compute an index, then the operation is performed directly at that array position, achieving high-speed access.


hash function

The hash function is the key to a hash table's efficiency; its design directly determines the frequency of collisions.

Properties of a good hash function

To evaluate a hash function, we mainly look at the following properties:

Feature Description Precedence
Definiteness The same input always produces the same output Required
Uniform distribution outputs are uniformly distributed across the hash table's range Required
Efficient computation the computation is simple and fast Important
Avalanche effect a tiny change in input causes a huge change in output Recommendation

Common hash functions

For different types of keys, there are several classic methods for constructing hash functions:

Type Example Applicable scenarios
Division (modulo) method hash = key % table_size Integer keys
Multiplication method hash = floor(key * A % 1 * table_size) Floating-point keys
Digit analysis method analyzes the distribution pattern of digits data with specific patterns
Mid-squares method hash = (key * key) // 10^(n/2) % table_size Numeric keys
String hashing processed character by character String keys

A simple hash function example

Suppose the key is a string and the array length is 10.

A simple approach is: add up the ASCII codes of each character in the string, then take the remainder modulo the array length.

Example

def

simple_hash

(

key

,

array_size

)

:

   

"""
    A simple string hash function.
    :param key: the input key (string)
    :param array_size: the size of the hash table array
    :return: the computed array index
    """

    total

=

0

   

for

char

in

key:

       

Convert each character to its ASCII code value and accumulate

        total +

=

ord

(

char

)

   

Take modulo the array size to ensure the index falls within the array range

   

return

total % array_size

Test our hash function

Note that "runoob" and "RUNOOB" differ in case, so their hash values also differ

keys_to_test

=

[

"runoob"

,

"RUNOOB"

,

"Alice"

,

"David"

]

array_size

=

10

print

(

"Simple hash function test results:"

)

for

key

in

keys_to_test:

    hash_index

=

simple_hash

(

key

,

array_size

)

   

print

(

f

" Key '{key}' -> hash index: {hash_index}"

)

Output result:

简单哈希函数测试结果:

  键 'runoob' -> 哈希索引: 1

  键 'RUNOOB' -> 哈希索引: 9

  键 'Alice' -> 哈希索引: 8

  键 'David' -> 哈希索引: 8

We can see that the keys runoob and RUNOOB with different cases produced completely different indices, reflecting the avalanche effect of the hash function.

but Alice and David both have index 8, so two different keys mapped to the same position.

This is the problem to be solved in the next section —Hash Collision。


Hash Collisions and Their Resolution

Hash Collisionrefers to two or more different keys producing the same array index after the hash function is applied.

It is like a cinema selling the same seat number to two audience members; clearly a set of rules is needed to handle this.

Collisions are inevitable: the range of hash values (the array size) is finite, while the possible keys are infinite.

There are two main classic methods for resolving collisions.

Separate chaining

This is the most commonly used method. Instead of storing data directly at each array position, it stores aLinked list(simulated with a list in Python), and conflicting key-value pairs are attached in sequence to the same linked list.

The complete flow for inserting a piece of data is:

  1. Use the hash function to compute the key's index and locate the corresponding bucket.
  2. If the bucket is empty, store the key-value pair directly.
  3. If the bucket is not empty (a collision occurred), traverse the linked list: if the key already exists, update its value; if not, append to the end of the list.

Example

class

HashTableChaining:

   

"""Implementation of a hash table using separate chaining to resolve collisions."""

   

def

init

(

self

,

size

=

10

)

:

       

"""Initialize the hash table.
        :param size: the initial size of the underlying array
        """

       

self

.

size

=

size

       

Create a list of size `size`, where each element is an empty list (representing a linked list, also called a "bucket")

       

self

.

table

=

[

[

]

for

_

in

range

(

size

)

]

   

def

_hash

(

self

,

key

)

:

       

"""Internal hash function: sum the ASCII codes of characters and take modulo the table size (deterministic, for easy demonstration)."""

        total

=

0

       

for

char

in

str

(

key

)

:

            total +

=

ord

(

char

)

       

return

total %

self

.

size

   

def

insert

(

self

,

key

,

value

)

:

       

"""Insert a key-value pair into the hash table."""

        index

=

self

._hash

(

key

)

        bucket

=

self

.

table

[

index

]

Get the "bucket" (linked list) corresponding to the index

       

Traverse the bucket to check whether the key already exists

       

for

i

,

(

k

,

v

)

in

enumerate

(

bucket

)

:

           

if

k

==

key:

               

Key already exists, update the value

                bucket

[

i

]

=

(

key

,

value

)

               

return

       

Key does not exist, append to the end of the linked list

        bucket.

append

(

(

key

,

value

)

)

   

def

get

(

self

,

key

)

:

       

"""Get a value by key. Return None if the key does not exist."""

        index

=

self

._hash

(

key

)

        bucket

=

self

.

table

[

index

]

       

for

k

,

v

in

bucket:

           

if

k

==

key:

               

return

v

       

return

None

Key does not exist

   

def

delete

(

self

,

key

)

:

       

"""Delete a key-value pair by key."""

        index

=

self

._hash

(

key

)

        bucket

=

self

.

table

[

index

]

       

for

i

,

(

k

,

v

)

in

enumerate

(

bucket

)

:

           

if

k

==

key:

               

del

bucket

[

i

]

Delete the entry from the linked list

               

return

True

Deletion successful

       

return

False

Key does not exist, deletion failed

   

def

display

(

self

)

:

       

"""Print all contents of the hash table."""

       

for

i

,

bucket

in

enumerate

(

self

.

table

)

:

           

print

(

f

"Index {i}: {bucket}"

)

Usage examples

print

(

"--- Separate chaining hash table example ---"

)

phone_book

=

HashTableChaining

(

5

)

phone_book.

insert

(

"Alice"

,

"123-4567"

)

phone_book.

insert

(

"Bob"

,

"987-6543"

)

phone_book.

insert

(

"Charlie"

,

"555-1234"

)

"David" and "Alice" both have hash index 3, causing a collision

phone_book.

insert

(

"David"

,

"111-2222"

)

print

(

"Hash table after insertion:"

)

phone_book.

display

(

)

print

(

f

"\nLook up 'Bob' phone: {phone_book.get('Bob')}"

)

print

(

f

"Look up non-existent 'Eve': {phone_book.get('Eve')}"

)

phone_book.

delete

(

"Charlie"

)

print

(

"\nHash table after deleting 'Charlie':"

)

phone_book.

display

(

)

Output result:

--- 链地址法哈希表示例 ---

Hash table after inserting data:

索引 0: [('Bob', '987-6543')]

索引 1: [('Charlie', '555-1234')]

索引 2: []

索引 3: [('Alice', '123-4567'), ('David', '111-2222')]

索引 4: []



查找 'Bob' 的电话: 987-6543

查找不存在的 'Eve': None



Delete the hash table after 'Charlie':

索引 0: [('Bob', '987-6543')]

索引 1: []

索引 2: []

索引 3: [('Alice', '123-4567'), ('David', '111-2222')]

索引 4: []

Note index 3: since the table size is only 5,Alice and David a collision occurred, and both key-value pairs are linked in the same bucket.

When searching, first compute index 3, then compare keys one by one within the linked list to find the correct value.

Engineering practice: When a linked list becomes too long, Java's HashMap converts the linked list into a red-black tree, reducing the worst-case lookup time from O(k) to O(log k)。

Open addressing

This method stores all elements in the array itself, without introducing extra linked lists.

When a collision occurs, it follows a certainprobing sequence(Probing Sequence) to find the next empty position in the array.

Type probing sequence Advantages Disadvantages
Linear probing h, h+1, h+2, ... simple and easy to implement, cache-friendly prone to clustering
Quadratic probing h, h+1², h+2², ... reduces clustering may not be able to probe all positions
Double hashing h, h+hash2(key), h+2*hash2(key), ... uniform distribution more complex computation

Here we implement the simplest approach, linear probing:

Example

class

HashTableLinearProbing:

   

"""Implementation of a hash table using open addressing with linear probing to resolve collisions."""

   

def

init

(

self

,

size

=

10

)

:

       

self

.

size

=

size

       

Use None to represent an empty slot; for simplicity, the "deletion" marker issue is not handled here

       

self

.

keys

=

[

None

]

       

self

.

values

=

[

None

]

   

def

_hash

(

self

,

key

)

:

       

"""Internal hash function: sum the ASCII codes of characters and take modulo the table size."""

        total

=

0

       

for

char

in

str

(

key

)

:

            total +

=

ord

(

char

)

       

return

total %

self

.

size

   

def

insert

(

self

,

key

,

value

)

:

        index

=

self

._hash

(

key

)

        original_index

=

index

       

Linear probing: find an empty slot or the same key

       

while

self

.

keys

[

index

]

is

not

None

:

           

if

self

.

keys

[

index

]

==

key:

               

Key already exists, update the value

               

self

.

values

[

index

]

=

value

               

return

            index

=

(

index +

1

)

%

self

.

size

Move to the next position (circular array)

           

if

index

==

original_index:

               

Have gone full circle, the table is full (in practice you should resize first)

               

raise

Exception

(

"Hash table is full"

)

       

Found an empty slot, insert

       

self

.

keys

[

index

]

=

key

       

self

.

values

[

index

]

=

value

   

def

get

(

self

,

key

)

:

        index

=

self

._hash

(

key

)

        original_index

=

index

       

Search along the same probing sequence used for insertion

       

while

self

.

keys

[

index

]

is

not

None

:

           

if

self

.

keys

[

index

]

==

key:

               

return

self

.

values

[

index

]

            index

=

(

index +

1

)

%

self

.

size

           

if

index

==

original_index:

               

break

Searched a full circle without finding it

       

return

None

   

def

display

(

self

)

:

       

for

i

in

range

(

self

.

size

)

:

           

if

self

.

keys

[

i

]

is

not

None

:

               

print

(

f

"Index {i}: key={self.keys[i]}, value={self.values[i]}"

)

           

else

:

               

print

(

f

"Index {i}: empty"

)

Usage examples

print

(

"--- Linear probing hash table example ---"

)

ht_linear

=

HashTableLinearProbing

(

7

)

A small size makes the probing process easy to see

Initial indices of the keys: Apple->1, Banana->3, runoob->3, Cherry->5

ht_linear.

insert

(

"Apple"

,

10

)

ht_linear.

insert

(

"Banana"

,

20

)

"runoob" and "Banana" collide (both index 3); probing forward to 4 to store

ht_linear.

insert

(

"runoob"

,

30

)

ht_linear.

insert

(

"Cherry"

,

40

)

print

(

"Hash table after insertion:"

)

ht_linear.

display

(

)

print

(

f

"\nLook up 'Banana': {ht_linear.get('Banana')}"

)

print

(

f

"Look up 'runoob' (stored after collision probing): {ht_linear.get('runoob')}"

)

Output result:

--- 线性探测哈希表示例 ---

Hash table after inserting data:

索引 0: 空

索引 1: 键=Apple, 值=10

索引 2: 空

索引 3: 键=Banana, 值=20

索引 4: 键=runoob, 值=30

索引 5: 键=Cherry, 值=40

索引 6: 空

runoob 's initial index is 3, but that position has been Banana occupied.

Linear probing moves forward one slot and finally stores it at index 4; when searching, following the same path will find it.

Note: Deletion in open addressing is tricky; you cannot simply set the position back to None, otherwise it breaks the probing sequence and later elements cannot be found.

The usual approach is to place a special "deleted" marker (lazy deletion), skip it during searching, and reuse it during insertion. For simplicity, this example does not implement deletion.

Comparison of the Two Methods

Both methods have trade-offs; the following table can guide practical selection:

Feature Separate chaining Open addressing
Implementation difficulty relatively simple relatively complex, especially deletion
Space overhead requires extra space to store pointers (linked lists) all data is in the array, so space utilization may be higher
Impact of collisions collisions only affect the performance of the same bucket (linked list) collisions occupy subsequent positions and may cause "clustering"
Resize timing resize when the average linked list length exceeds a threshold resize when the load factor (number of elements / array size) exceeds a threshold
Applicable scenarios general-purpose, more common cache-friendly, suitable for scenarios with a known maximum data size or tight memory


Performance and Load Factor

The efficiency of a hash table depends heavily on a key metric:load factor(Load Factor)。

Load factor = number of elements stored in the hash table ÷ total size of the hash table array.

load factor Meaning Impact on performance
low (e.g., 0.5) the array still has many empty slots low collision probability, fast operations
high (e.g., 0.9) the array is nearly full linked lists grow longer or probing distances grow longer, and performance drops noticeably

To maintain high performance, when the load factor exceeds a certain threshold (e.g., 0.75), the hash table performsresizing:

  1. Create a new, larger array (usually twice the original size).
  2. Traverse all key-value pairs in the old hash table.
  3. Recompute each key's index based on the new array size and insert into the new array.

This process is called Rehashing。

Although a single resize is time-consuming, it significantly lowers the load factor and restores the hash table's efficiency.

Since resizing is amortized over many insertion operations, the average insertion complexity of a hash table is still O(1)。


Practical Exercise: Build a Word Counter

Let's use our own separate-chaining hash table to solve a practical problem: counting the occurrences of each word in a piece of text.

The test text is as follows:

the quick brown fox jumps over the lazy dog i learn python on runoob and runoob is free

Example

Exercise: Use our implemented HashTableChaining to count word frequencies

print

(

"=== Practical Exercise: Word Counter ==="

)

1. Create a hash table instance

word_counter

=

HashTableChaining

(

size

=

10

)

2. The provided test text

text

=

"the quick brown fox jumps over the lazy dog i learn python on runoob and runoob is free"

words

=

text.

split

(

)

Split the text into a list of words

print

(

"Processed word list:"

,

words

)

3. Traverse the words and insert into the hash table

for

word

in

words:

    current_count

=

word_counter.

get

(

word

)

   

if

current_count

is

None

:

       

First occurrence of the word, count is 1

        word_counter.

insert

(

word

,

1

)

   

else

:

       

Word already exists, increment count by 1

        word_counter.

insert

(

word

,

current_count +

1

)

4. Output the statistics

display() prints by index; here we merge all buckets for a friendlier output

print

(

"\nWord occurrence counts:"

)

all_entries

=

[

]

for

bucket

in

word_counter.

table

:

    all_entries.

extend

(

bucket

)

Merge the entries from all buckets

for

word

,

count

in

all_entries:

   

print

(

f

" '{word}': {count} times"

)

5. Verify a specific word

test_word

=

"the"

print

(

f

"\nVerification: the word '{test_word}' appeared {word_counter.get(test_word)} times."

)

test_word

=

"runoob"

print

(

f

"\nVerification: the word '{test_word}' appeared {word_counter.get(test_word)} times."

)

Output result:

=== 实践练习:单词计数器 ===

处理的单词列表: ['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog', 'i', 'learn', 'python', 'on', 'runoob', 'and', 'runoob', 'is', 'free']



Word frequency count:

  'learn': 1 次

  'is': 1 次

  'the': 2 次

  'quick': 1 次

  'on': 1 次

  'runoob': 2 次

  'brown': 1 次

  'fox': 1 次

  'over': 1 次

  'dog': 1 次

  'python': 1 次

  'i': 1 次

  'and': 1 次

  'lazy': 1 次

  'free': 1 次

  'jumps': 1 次



验证:单词 'the' 出现了 2 次。

验证:单词 'runoob' 出现了 2 次。

You have successfully completed a practical task with your own hash table implementation.

In real development, you rarely need to write a hash table by hand, because modern programming languages provide highly optimized built-in implementations, such as Python's dict, Java's HashMap, and C++'s unordered_map。

Understanding their principles helps you use them more wisely and efficiently.


Summary and Key Takeaways

Finally, a table to review the core knowledge points of this article:

Key Points Description
What a hash table is an efficient data structure that accesses values directly by key, with average time complexity O(1)
Core mechanism the hash function converts keys into array indices
Key challenge hash collisions: different keys mapping to the same index, which is inevitable
Solution 1 separate chaining: each index position holds a linked list storing conflicting key-value pairs
Solution 2 open addressing: search for the next empty slot within the array along a probing sequence
Performance key when the load factor is too high, restore performance through resizing and rehashing
Practical applications database indexes, cache systems, set membership checks, object property storage, etc.