awelgorithms

Keys are unique values need not be

Updated

The map invariant is unique keys. Values have no uniqueness. {4:2, 1:2} is legal. Putting 4 again replaces. It does not create a second 4.

What to focus on

If you need unique values, that is a set of values, or you check contains-value before put, slowly. Grouping stores many values under one unique key as a list.

Worked examples

shared value

a = [4, 1], put both → 2
  1. two keys, one value repeated

Result: {4:2, 1:2} · size 2

unique keys

a = [4, 4], put 4→2 then 4→3
  1. still one key

Result: {4:3} · size 1

empty

a = []
  1. no keys to collide

Result: {}

Try it

Write put(m, k, v). m starts as {}. k is the key. v is the value. Keys stay unique. Values may repeat. Size is the number of keys. a = [4, 1], put both → 2 → {4:2, 1:2} · size 2. a = [4, 4], put 4→2 then 4→3 → {4:3} · size 1. a = [] → {}.

keys and values are integers. Start from {} and apply the listed puts.