KatInterview

Merging k Key-Value Maps: Conflict Rules and Efficient Design

Arrays & HashingModel answer
MediumModel answerArrays & Hashinghash-mapmergingapi-design

Last 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:

  1. Which questions would you ask before writing any code?
  2. What are the reasonable conflict-resolution policies, and when would each be appropriate?
  3. How do you merge two maps, and how do you generalize to k maps efficiently?
  4. 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.