awelgorithms

Put a key-value pair

Updated

Put installs (or replaces) the value for a key. Size grows only when the key was absent. After put(k,v), get(k) is v.

What to focus on

Put does not append a second slot for the same key. There is one entry per key.

Worked examples

new key

a = [4, 1, 9] as {4:2,1:8,9:3}, put 7→5
  1. 7 was absent
  2. size 3→4

Result: {4:2, 1:8, 9:3, 7:5}

replace

a = [4, 1, 9] as {4:2,1:8,9:3}, put 1→0
  1. 1 already present
  2. value 8→0
  3. size stays 3

Result: {4:2, 1:0, 9:3}

onto empty

a = [], put 4→2
  1. first entry

Result: {4:2}

Try it

Write put(m, k, v). m is the hash map. k is the key. v is the value. If k is new, size grows by 1. If k exists, replace the value and size stays. Then get(k) is v. a = [4, 1, 9] as {4:2,1:8,9:3}, put 7→5 → {4:2, 1:8, 9:3, 7:5}. a = [4, 1, 9] as {4:2,1:8,9:3}, put 1→0 → {4:2, 1:0, 9:3}. a = [], put 4→2 → {4:2}.

keys and values are integers. The map may be empty.