AlgoFrames

Implement insert with tombstones

Standard · Write code · about 20 min

Run commands on a table of size slots with linear probing and hash key mod size, without a built-in map or set. Every command returns one number:

  • insert K: if K is in the table, return its slot. Otherwise put K in the first tombstone on its probe sequence, else in the empty slot that ends the sequence. Return that slot.
  • delete K: if K is in the table, replace it with a tombstone and return its slot. Otherwise return −1.
  • find K: return the slot of K, or −1. Probes walk past tombstones and stop at an empty slot.

Return the results of all commands in order.

Example 1

Input:

[["insert 3","insert 11","insert 19","delete 11","find 19","insert 27","find 11"],8]

Output:

[3,4,5,4,5,4,-1]

find 19 walks past the tombstone at slot 4. insert 27 reuses that tombstone.

Example 2

Input:

[["insert 5","insert 5","delete 7","find 5"],4]

Output:

[1,1,-1,1]

A repeated insert returns the slot the key already has.

Constraints

  • 0 ≤ commands.length ≤ 10,000
  • 1 ≤ size ≤ 10,000 and 0 ≤ K ≤ 1,000,000
  • Fewer than size insert commands add a new key, so an empty slot always exists

Learn the idea first: Open addressing: linear, quadratic probing, double hashing, a visual lesson.

More Open addressing: linear, quadratic probing, double hashing problems