awelgorithms

Understand key versus value

Updated

The key is how you name the slot. The value is what lives in that slot. Get asks by key and returns a value. You do not get-by-value in O(1). Swapping the two is a different map.

What to focus on

In {4:2}, 4 is the key and 2 is the value. Looking up 2 is a miss unless 2 is also a key. Two keys may share a value. Two values cannot share a key.

Worked examples

named slot

a = [4], put 4→2
  1. key 4
  2. value 2

Result: get(4)=2, get(2) misses

same value two keys

a = [4, 1], both → 2
  1. 4→2 and 1→2
  2. keys still distinct

Result: {4:2, 1:2}

swap would differ

a = [4], put 4→2 versus put 2→4
  1. different key sets

Result: {4:2} is not {2:4}

Try it

Write get(m, k). m is the hash map of key to value. k is the key to look up. Return the value stored for k. get-by-value is not this operation. {4:2} is not {2:4}. a = [4], put 4→2 → get(4)=2, get(2) misses. a = [4, 1], both → 2 → {4:2, 1:2}. a = [4], put 4→2 versus put 2→4 → {4:2} is not {2:4}.

keys and values are integers. The map is non-empty after the first put.