Data Structures · Visualization
Hash Table: Introduction
Hash Table
A hash table stores key-value pairs and uses a 'hash function' to convert each key into a number, which becomes an index into an underlying array. Time: O(1) average for insert/get/delete, O(n) worst case with many collisions. Space: O(n).
Big-O: Average O(1) per operation; worst case O(n) on collisions.
Hash Table: Introduction
Hash TableA hash table stores key-value pairs and uses a 'hash function' to convert each key into a number, which becomes an index into an underlying array. This means you can jump almost directly to where a value is stored just by knowing its key, instead of searching through every item. When two different keys hash to the same index (a 'collision'), the table handles it, often by storing a small list of entries at that index (chaining).
How Hash Table: Introduction Works
- Choose an array ('buckets') of a fixed starting size.
- For each key, run it through a hash function to get a number.
- Reduce that number to a valid array index, usually with modulo (index = hash % arraySize).
- Store the key-value pair at that index (using chaining or another method to handle collisions).
Hash Table: Introduction Worked Example
Input: Store 'age' -> 30 in a table of size 5
- hash('age') might compute to, say, 372
- index = 372 % 5 = 2
- Store the pair ('age', 30) at bucket index 2
Output: bucket[2] = [('age', 30)]
Press ▶ Run to watch it step by step.
# Hash map: key -> value, O(1) average
scores = {}
scores["alice"] = 90 # insert
v = scores.get("bob", 0) # get with default
del scores["alice"] # delete
if "bob" in scores: # membership
print("present")
# example: intro key=age value=30Hash Table: Introduction Time & Space Complexity
When to Use Hash Table: Introduction
- Implementing dictionaries, objects, and sets in most programming languages
- Caching computed results for fast lookup (memoization)
- Counting frequencies of items (word counts, duplicate detection)
- Database indexing for fast record lookup
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.