User Tools

Site Tools


data-structures-algorithms:hash-table-concept

This is an old revision of the document!


Hash Table Concept

A hash table is a data structure that stores data as key-value pairs and uses a hash function to quickly compute the storage location.

Basic Idea

When we write:

set("abc") = "xyz"

Internally, it becomes:

index = hash("abc") % array_size
A[index] = ("abc", "xyz")

This means: - The key (“abc”) is passed into a hash function - The hash function converts it into a number - That number is reduced into a valid array index using modulo (%) - The value is stored together with the key at that index

Why store (key, value)?

We store both key and value because different keys can produce the same index (collision).

Example:

"abc" → index 2
"def" → index 2

If we store only values:

A[2] = "xyz"   ❌ (data will be overwritten)

Instead, we store:

A[2] = [
  ("abc", "xyz"),
  ("def", "123")
]

This method is called “chaining”.

Correct Mental Model

The correct way to think about a hash table is:

key → hash(key) → index → A[index] = (key, value)

or in real systems:

A[index] = list of (key, value)

Summary

- Hash table maps keys to values using a hash function - Index is computed as: hash(key) % array_size - Each slot stores (key, value), not just value - Collisions are handled using a list (chaining) - Average time complexity for get/set is O(1)

Key Insight

Hash tables are fast because they avoid searching through all elements by directly jumping to a computed index.

data-structures-algorithms/hash-table-concept.1779576422.txt.gz · Last modified: by phong2018