awelgorithms

Append to a list under a key

Updated

The mutation is: if absent, put key → [x]; else values.get(key).append(x). Do not put key → [x] on a later item. That overwrite drops the old list.

What to focus on

get-then-append needs the list to already exist. compute-if-absent / put-if-absent is the helper that creates [] once.

Worked examples

second append

a = [1, 9, 1], group by value, last 1
  1. 1 already [0]
  2. append index 2

Result: 1→[0,2] if a=[1,9,1]

first creates

a = [4, 1, 9], first 9
  1. 9 absent
  2. put [2]

Result: 9→[2]

empty start

a = [], append 4 under key 0
  1. create list

Result: {0:[4]}

Try it

Write append(m, k, x). m is a map from key to list. k is the key. x is the item to append. If k is absent, put [x]. Else append x onto the existing list. Do not replace the list with [x]. a = [1, 9, 1], group by value, last 1 → 1→[0,2] if a=[1,9,1]. a = [4, 1, 9], first 9 → 9→[2]. a = [], append 4 under key 0 → {0:[4]}.

keys are integers. Values under a key are lists.

LeetCode problems that use this skill