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 TableInserting 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
- Compute the hash of the key and convert it to a bucket index.
- Look in that bucket to see if the key already exists.
- If it exists, update its value.
- 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
- hash('name') % size = 3
- Bucket 3 is empty (or checked for the key 'name')
- Add ('name', 'Sam') to bucket 3
Output: bucket[3] = [('name', 'Sam')]
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: insert key=name value=SamBehind 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
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
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.