Merge two maps by adding counts
Updated
Merging two count maps adds the counts of shared keys and keeps the keys that appear in only one map. The result has |keysA ∪ keysB| entries.
What to focus on
Copy a, then walk b: for each key add its count to the existing value or insert it. Never assume iteration order.
Worked examples
disjoint
a = {4: 2}, b = {1: 8}- no shared key
Result: {4: 2, 1: 8}
shared key
a = {4: 1, 1: 2}, b = {1: 1, 9: 1}- 1: 2 + 1
Result: {4: 1, 1: 3, 9: 1}
empty a
a = {}, b = {4: 2}- copy b
Result: {4: 2}
Try it
Write addCounts(a, b). a and b are maps from integer keys to integer counts. Either may be empty. Return a new map holding every key from both, with the counts of shared keys added together. a = {4: 2}, b = {1: 8} → {4: 2, 1: 8}. a = {4: 1, 1: 2}, b = {1: 1, 9: 1} → {4: 1, 1: 3, 9: 1}. a = {}, b = {4: 2} → {4: 2}.
keys and counts are integers. Either map may be empty.