awelgorithms

Distinguish a missing key from value zero

Updated

contains-key is the test for presence. get returning 0 might mean stored 0 or I defaulted a miss to 0. If 0 is a legal value, you cannot use 0 as a miss signal.

What to focus on

Frequency maps store 0 only if you insert zeros. Usually absent means count 0 and you must not confuse that with an explicit {k:0} you forgot to delete.

Worked examples

stored zero

a = [4] as {4:0}, get 4
  1. key present
  2. value is 0

Result: [true, 0]

absent

a = [4] as {4:0}, get 1
  1. 1 not a key

Result: [false, miss]

empty

a = [], get 0
  1. 0 as key is also absent

Result: [false, miss]

Try it

Write probe(m, k). m is the hash map. k is the key. 0 is a legal value and a legal key. Return [hasKey(m, k), getOrMiss(m, k)] where miss is the sentinel miss, never 0. {4:0} get 4 → [true, 0]. get 1 → [false, miss]. {} get 0 → [false, miss].

keys are integers. 0 is a legal value and a legal key.