Merge Counters
A medium Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- medium
- Seniority
- L3
Problem
Given two dicts d1 and d2 mapping keys to numbers, return a new dict combining all keys. For keys present in both, sum the two values. For keys in only one, keep that value.
Two tallies. Combine them.
Example 1
Input:
d1 = {"a":1,"b":2}, d2 = {"b":3,"c":4}Output:
{"a":1,"b":5,"c":4}Example 2
Input:
d1 = {}, d2 = {}Output:
{}Worked solution and explanation
Why this problem exists in real interviews
Merging two counter dicts by summing shared keys is a reduce operation common in MapReduce-style pipelines. It tests whether you handle keys unique to each dict correctly.
Break down the requirements
Step 1: Start with all keys from both dicts
The merged result contains every key that appears in either dict.
Step 2: Sum values for shared keys
When both dicts have the same key, add their values.
Step 3: Pass through unique keys unchanged
Keys in only one dict appear with their original value.
The solution
def merge_dicts(d1, d2):
result = {}
for key in d1:
result[key] = d1[key]
for key in d2:
if key in result:
result[key] += d2[key]
else:
result[key] = d2[key]
return resultCommon follow-up questions
- How would you merge N counter dicts? (Tests folding with functools.reduce or iterating over a list of dicts.)
- What if some values are negative? (Tests that the summation handles negative counts correctly without special casing.)
- How does collections.Counter handle this? (Tests knowledge that `Counter(d1) + Counter(d2)` only keeps positive counts, dropping zero or negative results.)