Data Structures · Visualization

Hash Table: Insert

Hash Table

Inserting adds a new key-value pair, or updates the value if the key already exists. Time: O(1) average, O(n) worst case. Space: O(1) per insert.

Big-O: Average O(1) per operation; worst case O(n) on collisions.

Hash Table: Insert

Hash Table

Inserting adds a new key-value pair, or updates the value if the key already exists. The key is hashed to find its bucket, and the pair is stored there — if another key already occupies that bucket (a collision), it is added alongside it rather than overwriting it.

How Insert Works

  1. Compute the hash of the key and convert it to a bucket index.
  2. Look in that bucket to see if the key already exists.
  3. If it exists, update its value.
  4. If it does not exist, add the new key-value pair to the bucket.

Insert Worked Example

Input: Insert ('name', 'Sam') into a hash table

  1. hash('name') % size = 3
  2. Bucket 3 is empty (or checked for the key 'name')
  3. Add ('name', 'Sam') to bucket 3

Output: bucket[3] = [('name', 'Sam')]

Try your own input
Hash Table: Introduction
Runs each key through a hash function to compute a bucket index, so lookups don’t need to scan every entry.
0
∅
1
∅
2
∅
3
∅
4
∅
5
∅
6
∅
Active Hash map Key
Hash Table: Introduction
Press ▶ Run to watch it step by step.
Python · Hash Tables in Code
# 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: insert key=name value=Sam
Input: Insert ('name', 'Sam') into a hash table

Behind the Scenes Execution

Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.

Insert Time & Space Complexity

TimeO(1) average, O(n) worst case
SpaceO(1) per insert

When to Use Insert

  • Adding a new user record keyed by user ID
  • Storing a newly computed cache result
  • Adding a word to a frequency counter

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Ready for the next step?

See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.