awelgorithms

Update a map value in place

Updated

In-place update reads the old value, computes a new one, and puts it back under the same key. Size unchanged.

What to focus on

Examples: count++, list append, running max. The key set does not grow unless you insert a new key.

Worked examples

add to value

a = [4] as {4:2}, put 4→2+3
  1. same key
  2. value 5

Result: {4:5}

append in list

a = [4] as {4:[2]}, append 8
  1. list grows

Result: {4:[2,8]}

missing

a = [], update 4 by +1
  1. no old value
  2. start at 1 if count

Result: {4:1}

Try it

Write update(m, k, next). m is the hash map. k is a present key. next is the new scalar or the item to append. Put the new value under the same key. Size unchanged. a = [4] as {4:2}, put 4→2+3 → {4:5}. a = [4] as {4:[2]}, append 8 → {4:[2,8]}. a = [], update 4 by +1 → {4:1}.

keys are integers. The key exists when you update a scalar or list in place.