# Merge Counters

> Two tallies. Combine them.

Canonical URL: <https://datadriven.io/problems/merge_counters>

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.

## 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

**Union-key merge with value summation**

```python
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 result
```

> **Time and Space Complexity**
>
> **Time:** O(n + m) where n and m are the sizes of the two dicts.
> 
> **Space:** O(n + m) for the merged result.

> **Interviewers Watch For**
>
> Whether you mention `collections.Counter` which supports `+` operator for merging. Writing the manual version shows you understand the mechanics.

> **Common Pitfall**
>
> Modifying `d1` in place instead of creating a new dict. This mutates the caller's data, which is a common source of bugs in production.

---

## Common 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.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/merge_counters)
- [Python Interview Questions](https://datadriven.io/python-interview-questions)
- [Data Engineering Interview Prep Guide](https://datadriven.io/data-engineer-interview-prep)
- [Daily Challenge](https://datadriven.io/daily)

---

Source: DataDriven (https://datadriven.io). 100% free data engineering interview prep. Live code execution against Postgres 16, Python 3.11, and Spark sandboxes. No paywall, no premium tier, no signup gate.