AlgoFrames

Implement get and put

Standard · Write code · about 15 min

Build a hash table with separate chaining and run a list of commands on it. Use 8 buckets, each a list of [key, value] pairs, and hash a key with key mod 8. Do not use a built-in map or dictionary.

put K V stores value V under key K. If K already exists, replace its value. get K returns the value of K, or "-1" if K is missing.

Return the results of the get commands in order. put produces no output.

Example 1

Input:

[["put 5 50","put 13 130","get 13","get 5","get 21"]]

Output:

["130","50","-1"]

5 and 13 share bucket 5, so get 13 walks past 5.

Example 2

Input:

[["put 3 1","put 3 2","get 3"]]

Output:

["2"]

The second put replaces the value.

Constraints

  • 0 ≤ commands.length ≤ 10,000
  • 0 ≤ K ≤ 1,000,000 and V is a whole number written as text
  • Each command is put K V or get K

Learn the idea first: Hash tables with separate chaining, a visual lesson.

More Hash tables with separate chaining problems