DSA Hashing Foundation

Hashing Foundation

What is hashing

Hashing turns a key into a small integer so you can jump straight to a bucket instead of scanning a list. A hash table stores those buckets. Average insert, search, and delete are O(1). When two keys land in the same bucket, that is a collision — they chain together in that slot.

  • Hash function: maps a key to a bucket number. This page uses key % 8.
  • Bucket array: a fixed list of slots. The index is where the key should live.
  • Collision: two different keys can share a bucket. Separate chaining keeps a short list in that slot.
  • Why it shows up in interviews: membership tests, frequency counts, and “have I seen this before?” in expected O(1). Python dict / set, C++ unordered_map, Java HashMap.

Try it

Insert keys and watch hash(key) = key % 8 choose a bucket. Try 10, then 18, then 26 — they collide in bucket 2 and form a chain. Search highlights a hit in green. Delete removes one node from the chain.

hash_table — 8 buckets, separate chaining

hash(key) = key % 8
Empty table. Insert a key to start.

Pseudocode & complexity

pseudocode.txt

1function hash(key):
2  return key % BUCKETS
3
4function insert(key):
5  table[hash(key)].append(key)
6
7function search(key):
8  return key in table[hash(key)]

complexity.md

OperationAverageWorst
InsertO(1)O(n)
SearchO(1)O(n)
DeleteO(1)O(n)

Python set / dict

hashing.py

1# Membership and counts — the two hashing patterns you will use most
2seen = set()
3seen.add(10)
4if 10 in seen:
5  print("hit")
6
7freq = {}
8for x in nums:
9  freq[x] = freq.get(x, 0) + 1