Merging k Key-Value Maps: Conflict Rules and Efficient Design
Arrays & HashingModel answerLast updated
Design a way to merge two key-value maps, extend it to k maps, and decide which conflict rules must be pinned down before writing any code.
You are asked to write a routine that combines two key-value maps (dictionaries) into one, and then extend it so it works for k maps.
The request deliberately leaves out what should happen when the same key shows up in more than one input. Your job is not only to produce code but also to show how you would handle this ambiguity.
Please cover the following in your answer:
- Which questions would you ask before writing any code?
- What are the reasonable conflict-resolution policies, and when would each be appropriate?
- How do you merge two maps, and how do you generalize to
kmaps efficiently? - What are the time and space costs, and what changes if inputs must not be mutated, if key order matters, or if the work must be parallelized?
Assumptions and notes:
- Do not quietly pick a rule such as "first value wins," "last value wins," "add the values," or "gather all values into a list." Each yields different output, so the choice has to be explicit.
- Consider whether inputs may be modified and whether the order of keys in the result is meaningful.
Hints
Hint 1
Before coding, list the situations where the answer is not unique: a key present in several inputs with different values, and also a key present with equal values.
Hint 2
Think of the k-map merge as a single pass over every (key, value) pair of every input, applying a conflict function when the key is already in the result.
Hint 3
If the conflict function is associative (for example sum, max, or list concatenation), the work can be split across workers or done as a tree of pairwise merges; if it is order-dependent (last wins), the order of inputs must be preserved.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify first
The task as stated has no unique answer, so I would ask:
- Conflict rule: If key
ais in several maps with different values, what should the output hold? Do equal values count as a conflict, or are they fine? - Combinability: Can values be combined (numbers added, sets unioned, lists concatenated)? Is the combine operation associative and, ideally, commutative?
- Ordering: Does key order in the output matter (insertion order, sorted, irrelevant)? Does the order of the input maps carry priority?
- Mutation: May I modify one of the inputs in place, or must all inputs stay untouched and a new map be returned?
- Scale: Are the maps small, or large enough that memory or parallelism matters? Are values nested maps that should be merged recursively?
- Bad data: What about
nullvalues, unhashable keys, or non-comparable values?
2. Conflict policies
| Policy | Result on key a | Typical use |
|---|---|---|
| Last wins | value from the latest map | Config overrides, defaults then user settings |
| First wins | value from the earliest map | Keeping existing data, "fill only missing" |
| Combine (sum, max, min) | f(old, new) | Counters, aggregated metrics |
| Collect | list or set of all values | Preserving full information, later resolution |
| Error on conflict | raise if values differ | Strict data integrity, schema merges |
| Recursive | merge nested maps by the same rule | Nested configuration |
Trade-offs: last/first wins silently discards data, which is dangerous if unintended. Collect keeps everything but changes the value type (a scalar becomes a list), which affects downstream code. Error-on-conflict is safest but may be too strict. Combine functions need clear semantics for missing keys (an identity element helps).
3. Algorithm
Generalize with a single policy function resolve(old, new).
def merge_all(maps, resolve=lambda old, new: new):
result = {}
for m in maps: # input order defines priority
for key, value in m.items():
if key in result:
result[key] = resolve(result[key], value)
else:
result[key] = value
return result
Two maps is just merge_all([a, b]). Examples:
- Last wins: default
resolveabove (equivalent to Python's{**a, **b}or repeateddict.update). - First wins:
resolve=lambda old, new: old. - Sum:
resolve=lambda old, new: old + new. - Collect: wrap each first value in a list and use
old + [new], or use adefaultdict(list)and append. - Strict:
resolveraises ifold != new.
Why not merge pairwise in a loop?
The naive result = merge(result, m) is fine if each merge only inserts the new map's entries into the accumulator (cost proportional to the size of m). It becomes quadratic if each step copies the whole accumulator, for example result = {**result, **m} inside a loop. That copies the growing result k times, giving roughly O(k * N) instead of O(N). Always accumulate into one result dictionary.
4. Complexity
Let N be the total number of entries across all inputs and U the number of distinct keys.
- Time:
O(N)expected, since each entry costs one hash lookup and at most one write. Theresolvefunction adds its own cost (for collect, appends are amortizedO(1)). - Space:
O(U)for the output (plusO(N)for the collect policy, which keeps every value). In-place merging into the first map can avoid allocating a new container but mutates the caller's data.
5. Variations and trade-offs
- Immutability: Copy the first map (
O(size)) and merge the rest into the copy, or start from an empty result. Document which one is chosen. Shallow copies share nested objects; use recursive merging or deep copy if nested values may be changed later. - Ordering: Python dicts preserve first-insertion order of keys, so a overridden key keeps its original position under the loop above. If the "last map's position" matters, delete and reinsert, or state the rule. If sorted output is needed, sorting adds
O(U log U). - Parallelism: If
resolveis associative (sum, max, union, list concatenation that preserves order), split the maps into groups, merge each group in parallel, and then merge the partial results in a tree, givingO(log k)merge rounds. Last-wins is also associative as long as the group order is preserved. A non-associative rule (for example average computed pairwise) must instead collect values and compute once at the end, or carry(sum, count)pairs. - Streaming / huge inputs: If maps do not fit in memory, partition by hash of the key so each partition's merge is independent (this is the same idea as a shuffle in MapReduce).
- Nested maps: Make
resolverecursive when both values are maps; otherwise fall back to the base rule.
6. Common mistakes
- Choosing "last wins" without saying so, then being surprised when the caller expected a sum.
- Mutating an input map that the caller still uses.
- Quadratic copying in a loop of
{**acc, **m}. - Assuming key order is stable or meaningful without checking the language guarantees.
- Treating
Noneor falsy values as "missing" (for exampleif not result.get(key)), which can overwrite legitimate zeros or empty strings. Use a membership test instead. - Using a non-associative combine function and then parallelizing, which yields results that depend on scheduling.
7. Testing
Cover: no maps, one map, empty maps, disjoint keys, fully overlapping keys, equal values for the same key, differing values, three or more maps with the same key (to check priority order), falsy values (0, "", None), and verify that inputs are unchanged when immutability is required.