awelgorithms

Supply a default for a missing key

Updated

getOrDefault(k, d) returns the stored value if k is present, else d, without inserting k. That is different from put-if-absent, which writes d. Pick the one the spec wants.

What to focus on

A common default is 0 for counts. Using 0 as default does not mean 0 was stored. After getOrDefault, size is unchanged unless you also put.

Worked examples

present ignores default

a = [4, 1, 9] as {4:2,1:8,9:3}, getOrDefault(1, 0)
  1. 1 is present

Result: 8, not 0

absent uses default

a = [4, 1, 9] as {4:2,1:8,9:3}, getOrDefault(7, 0)
  1. 7 missing
  2. do not insert 7

Result: 0, map unchanged

empty

a = [], getOrDefault(4, -1)
  1. every key absent

Result: -1, still {}

Try it

Write getOrDefault(m, k, d). m is the hash map. k is the key. d is the default integer. If k is present, return its value. Else return d without inserting k. a = [4, 1, 9] as {4:2,1:8,9:3}, getOrDefault(1, 0) → 8, not 0. a = [4, 1, 9] as {4:2,1:8,9:3}, getOrDefault(7, 0) → 0, map unchanged. a = [], getOrDefault(4, -1) → -1, still {}.

keys and values are integers. Default d is an integer. Absent keys are not inserted.