awelgorithms

Decrement a count and maybe remove

Updated

Decrement is put(k, get(k)−1) when k is present. If the new count is 0, delete k. Otherwise later has-key is true with a stale zero, and size is wrong for how many distinct.

What to focus on

Do not go negative. Delete at zero so distinct-count stays the number of keys.

Worked examples

drop to zero

a = [4] as {4:1}, dec 4
  1. 1−1=0
  2. delete 4

Result: {}

stay positive

a = [4, 1, 9, 1] as {4:1,1:2,9:1}, dec 1
  1. 2−1=1
  2. keep key 1

Result: {4:1, 1:1, 9:1}

missing

a = [4] as {4:1}, dec 1
  1. 1 absent

Result: {4:1} unchanged (no-op)

Try it

Write dec(m, k). m is the frequency map. k is present and its count is ≥ 1. Subtract 1. If the new count is 0, delete k. Do not go negative. a = [4] as {4:1}, dec 4 → {}. a = [4, 1, 9, 1] as {4:1,1:2,9:1}, dec 1 → {4:1, 1:1, 9:1}. a = [4] as {4:1}, dec 1 → {4:1} unchanged (no-op).

keys are integers. The key is present and its count is ≥ 1.