Hash Deletion
In the past few lessons, we covered how to insert new items into separate chaining and open addressing hash tables. Let's also now take a look at how to delete an item from a hash table.
Separate chaining
Deleting a key x
is relatively simple in a separate chaining hash table. The algorithm is:
- Compute
h(x)
to find the bucket wherex
belongs. - Use the linked list deletion algorithm to delete the node with key
x
.
Open addressing
Deletion in an open addressing hash table is a little bit more challenging, since it can leave gaps in the table that interfere with the probing process. Watch the following video to see why deletion can create gaps, and how to fix it:
To summarize:
- When deleting an item, assign a special "removed" value to that slot in the table.
- For example, "empty" spaces may contain -1 and "removed" spaces may contain -2 as sentinel values
- When performing lookups, we need to skip past any removed slots and continue searching
- When performing insertions, we can insert into either empty or removed slots (whichever comes first), after checking to make sure the key to be inserted doesn't already exist