What is a Hash Table?
Data Structures·6 min·Python code
Hash tables store key and value pairs and find any value in O(1) time on average. Hash functions convert every key into an array index, and chaining handles keys that share a slot.
How Hash Tables Compute Where a Value Lives
Picture looking up a friend's phone number. Lists make you scan every name, while hash tables do arithmetic on the name and jump straight to the slot that holds the number.
Computing a location from the key is the trick that makes lookups feel instant. You give up order in exchange, because hash tables cannot return sorted keys or answer what the next largest key is.
In return you get near constant time insert, lookup and delete, which is the trade most interview problems ask for.
How Hashing Maps a Key to an Index
Hash functions take keys of almost any type, like strings, numbers or tuples, and return fixed size integers. Tables take that integer modulo the bucket count to get an array index and store the key and value pair there.
Indexing an array costs O(1) and a good hash function spreads keys evenly, so most operations touch one slot.
Load factor, which is items divided by buckets, climbs as you add entries. Past a set threshold, like 0.75 in Java's HashMap, the table allocates a larger array and rehashes every key. Resizing costs O(n) but happens rarely, so cost per operation stays O(1) amortised.
Collisions and Separate Chaining
Different keys can hash to the same index, which is a collision, and every real implementation needs a plan for it. Separate chaining gives every bucket a small list, and colliding entries live in that list.
Lookups find the bucket and scan its short list for the matching key. Open addressing is the alternative, and it probes forward to the next free slot instead of keeping lists.
Collisions make O(1) an average, not a guarantee. If all keys collided into one bucket, a lookup would degrade to O(n), a plain linear scan. Good hash functions and bounded load factors keep chains short.
Untrusted keys matter too, because inputs engineered to collide can force the worst case on purpose.
Practise lookups on CodeStory's hash table practice problems.
Hash Table Code Example in Python
class HashTable:
def __init__(self, capacity=8):
self.buckets = [[] for _ in range(capacity)]
self.size = 0
def _index(self, key):
return hash(key) % len(self.buckets)
def put(self, key, value):
bucket = self.buckets[self._index(key)]
for i, (k, _) in enumerate(bucket):
if k == key: # key exists -> overwrite
bucket[i] = (key, value)
return
bucket.append((key, value)) # new key -> chain it
self.size += 1
def get(self, key):
bucket = self.buckets[self._index(key)]
for k, v in bucket:
if k == key:
return v
raise KeyError(key)
Edit this code in the browser IDE on CodeStory, free on the platform. Open the CodeStory App
Hash Table Time and Space Complexity
| Time | O(1) average for insert, lookup and delete. O(n) worst case when many keys collide into one bucket |
|---|---|
| Space | O(n) for n stored entries |
O(1) is an amortised average that assumes a good hash function and a bounded load factor. Clustered or adversarial keys, or a table that never resizes, push operations toward O(n).
Watch Hashing Step by Step
Seeing a key land in a bucket on your own input shows how lookups skip scanning. Follow either of these one step at a time.
When to Use a Hash Table
- Membership tests, where a set of seen items answers have I seen this before in O(1) instead of rescanning a list.
- Frequency counting, where you map every item to a count for characters, words or anagram groups.
- Caching and memoization, where results are stored by input so no call is computed twice.
- Collapsing nested loops, where a single pass with a hash map replaces an O(n²) pair search, like the classic Two Sum trick.
Mistakes to Avoid
- Assuming O(1) always holds. Poor hash functions or adversarial keys can collide everything into one bucket and degrade operations to O(n).
- Using mutable or unhashable keys. Python lists cannot be keys, and mutating a key after insertion makes the entry impossible to find.
- Expecting order. Hash tables do not store keys sorted, so choose a balanced tree or sorted structure for range queries or ordered traversal.
Hash Table FAQs
What is the time complexity of a hash table?
Insert, lookup and delete cost O(1) on average. Worst case is O(n), when many keys collide into one bucket and the operation scans a list. Decent hash functions and bounded load factors make the average dependable.
Is a hash table hard to learn?
No. Hash tables map a key to an index with a function, and the value sits there. Collisions, load factor and resizing are the trickier parts, and they click once you watch a key land in a bucket step by step.
What is the difference between a hash table and a hash map?
They name the same key and value structure. Hash table is the classic data structure name, and hash map is a common implementation name, like Java's HashMap and C++'s unordered_map. Python calls it a dict. Hash sets store only keys for membership tests.
When should I use a hash table instead of an array?
Use hashing when you look things up by key rather than position or need membership checks, counting or deduplication. Use an array for ordered data, index access or range queries. Many interview fixes swap an array scan for a hash lookup to drop from O(n²) to O(n).
What is a collision in a hash table?
Collisions happen when two different keys hash to the same index. Separate chaining stores both in one bucket list, and open addressing probes for the next free slot.
What is load factor in a hash table?
Load factor is the number of items divided by the number of buckets. When it passes a threshold, the table grows and rehashes every key, which keeps chains short.
How do I practise hashing on CodeStory?
Follow Two Sum and Subarray Sum Equals K in the visualisers, and test your own keys on CodeStory's hash table practice problems.
Related Guides
Guides are step one. In a CodeStory batch you code the hash function yourself, then explain every collision in a scored mock round.
Talk to a Mentor