Taro Logo

Deep Merge of Two Objects

Medium
Asked by:
Valve
1 view
Topics:
ArraysRecursion

Given two values obj1 and obj2, return a deepmerged value.

Values should be deepmerged according to these rules:

  • If the two values are objects, the resulting object should have all the keys that exist on either object. If a key belongs to both objects, deepmerge the two associated values. Otherwise, add the key-value pair to the resulting object.
  • If the two values are arrays, the resulting array should be the same length as the longer array. Apply the same logic as you would with objects, but treat the indices as keys.
  • Otherwise the resulting value is obj2.

You can assume obj1 and obj2 are the output of JSON.parse().

Example 1:

Input: obj1 = {"a": 1, "c": 3}, obj2 = {"a": 2, "b": 2}
Output: {"a": 2, "c": 3, "b": 2}
Explanation: The value of obj1["a"] changed to 2 because if both objects have the same key and their value is not an array or object then we change the obj1 value to the obj2 value. Key "b" with value was added to obj1 as it doesn't exist in obj1. 

Example 2:

Input: obj1 = [{}, 2, 3], obj2 = [[], 5]
Output: [[], 5, 3]
Explanation: result[0] = obj2[0] because obj1[0] and obj2[0] have different types. result[2] = obj1[2] because obj2[2] does not exist.

Example 3:

Input: 
obj1 = {"a": 1, "b": {"c": [1 , [2, 7], 5], "d": 2}}, 
obj2 = {"a": 1, "b": {"c": [6, [6], [9]], "e": 3}}
Output: {"a": 1, "b": {"c": [6, [6, 7], [9]], "d": 2, "e": 3}}
Explanation: 
Arrays obj1["b"]["c"] and obj2["b"]["c"] have been merged in way that obj2 values overwrite obj1 values deeply only if they are not arrays or objects.
obj2["b"]["c"] has key "e" that obj1 doesn't have so it's added to obj1.

Example 4:

Input: obj1 = true, obj2 = null
Output: null

Constraints:

  • obj1 and obj2 are valid JSON values
  • 1 <= JSON.stringify(obj1).length <= 5 * 105
  • 1 <= JSON.stringify(obj2).length <= 5 * 105

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. How should we handle conflicts between different data types (e.g., if a property in `obj1` is a primitive or an array, but the same property in `obj2` is a nested object)?
  2. How should arrays be merged? Should `obj2`'s array completely overwrite `obj1`'s array, or should they be concatenated/merged by index?
  3. How should special JavaScript data types like `Date`, `RegExp`, `null`, or `undefined` values be handled if they are encountered as property values?
  4. Should the deep merge mutate `obj1` in place, or should we return a brand-new object without modifying either of the original inputs?
  5. Can the input objects contain circular references, or can we safely assume they are standard acyclic JSON objects?

Brute Force Solution

Approach

Imagine you have two complex filing systems containing folders and documents, and you want to combine them into one master system. The brute force approach involves looking at every single folder and piece of paper in both systems from scratch and copying them over one by one.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the very first folder in the first system and note all its contents.
  2. Go to the second system and search through every single folder to see if there is one with the exact same name.
  3. If you find a matching folder in the second system, open it up and compare all its contents piece by piece with the first one.
  4. If both systems have a value for the exact same item, completely erase the old value from the first system and replace it with the new value from the second system.
  5. If the second system contains folders or items that do not exist at all in the first system, simply take them and add them into the first system.
  6. Repeat this exhaustive checking process for every single nested folder and subfolder until every item from the second system has been processed and merged into a fresh copy of the first system.

Code Implementation

def deep_merge_objects(target_object, source_object):
    
    # We create a fresh copy to prevent mutating the original input dictionaries directly.
    result_object = dict(target_object)
    
    for source_key, source_value in source_object.items():
        if source_key in result_object:
            target_value = result_object[source_key]
            
            # We recursively merge nested dictionaries when both objects share the same key.
            if isinstance(target_value, dict) and isinstance(source_value, dict):
                result_object[source_key] = deep_merge_objects(target_value, source_value)
            else:
                result_object[source_key] = source_value
        else:
            # New keys from the source are safely copied over since they do not collide.
            result_object[source_key] = source_value
            
    return result_object

Big(O) Analysis

Time Complexity
O(n + m) – To deeply merge two object hierarchies, we must traverse every single property and nested subfolder across both input systems. If n represents the total number of properties, keys, and nested nodes in the first object, and m represents the total number of unique nodes in the second object, we must visit each node at least once to compare and combine them. The total operations scale linearly with the combined size of both trees, approximating n + m total visits. Consequently, this exhaustive traversal simplifies to a Big O time complexity of O(n + m).
Space Complexity
O(D) – The auxiliary space is driven by the call stack during recursive depth-first traversal of the nested objects and folders. In the worst-case scenario where the nested object hierarchies are deeply chained, the recursive calls will reach a maximum depth equal to D, which represents the maximum nesting level of the objects. Each stack frame consumes memory to keep track of the current keys and object references being compared and merged. Therefore, the extra memory required scales linearly with the maximum nesting depth rather than the total number of items, simplifying to Big O of D.

Optimal Solution

Approach

To combine two complex boxes of items cleanly, we can look inside both boxes at the same time and match up their contents. If both boxes have items with the exact same labels, we carefully open those matching items and combine their contents together.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the first box of items and prepare to compare it with the second box.
  2. Take each item from the second box and check if the first box already has something with the exact same label.
  3. If the first box does not have that item, simply place the item from the second box directly into the first box.
  4. If both boxes contain items with the same label, look inside those specific items to see what they hold.
  5. If both of those inner contents are also structured like boxes filled with items, repeat the matching process on them rather than just replacing one with the other.
  6. If the inner contents are regular items instead of boxes, let the item from the second box replace the one in the first box.
  7. Continue this process until all contents from the second box are fully integrated into the first box, resulting in a single perfectly combined box.

Code Implementation

def deep_merge_objects(target_dictionary, source_dictionary):
    # Iterate through keys in source to integrate them into target dictionary.
    for dictionary_key, source_value in source_dictionary.items():

        if dictionary_key not in target_dictionary:
            target_dictionary[dictionary_key] = source_value
        else:
            target_value = target_dictionary[dictionary_key]

            # Recursively merge nested dictionaries to combine inner contents.
            if isinstance(target_value, dict) and isinstance(source_value, dict):
                deep_merge_objects(target_value, source_value)
            else:
                # Overwrite scalar values when keys clash and they are not both dictionaries.
                target_dictionary[dictionary_key] = source_value

    return target_dictionary

Big(O) Analysis

Time Complexity
O(n) – To analyze the deep merge operation, let n represent the total number of keys and nested properties across both input objects. The algorithm recursively traverses every key-value pair in both objects, visiting each unique property at most once to compare and combine them. At each step, if a key exists in both objects and both values are nested structures, the algorithm dives deeper without redundant checks. This ensures the total number of operations scales linearly with the total count of properties, leading to an overall time complexity of O(n).
Space Complexity
O(D) – The auxiliary space is primarily determined by the call stack frames created during the recursive traversal of the nested object structures. Assuming N represents the total number of nested keys and properties across both objects, the maximum depth of the recursion reaches D, where D is the maximum nesting level of the objects. Therefore, the memory consumed by the recursion stack frames grows proportionally to this maximum depth D, resulting in an auxiliary space complexity of O(D) in the worst-case scenario.

Edge Cases

Null or undefined inputs for obj1 or obj2
How to Handle:
Check if either object is null, non-object, or primitive, and safely return the other object or a fallback.
Circular references within nested objects
How to Handle:
Maintain a visited map or weak map to track already merged object references and prevent infinite recursion.
Merging arrays instead of replacing them
How to Handle:
Determine whether arrays should be concatenated, overwritten entirely, or merged by index according to specific deep merge conventions.
Properties with undefined or null values in obj2 overriding valid values in obj1
How to Handle:
Explicitly check if the incoming value is undefined before overwriting, or allow explicit null overrides depending on the specification.
Deeply nested objects exceeding maximum call stack size
How to Handle:
Implement an iterative approach using an explicit stack or queue to handle arbitrary nesting depths without stack overflow.
Non-plain objects like Date, RegExp, or class instances
How to Handle:
Check object prototypes or constructors to clone specialized types properly rather than flattening them into plain objects.
Prototype pollution via keys like __proto__ or constructor
How to Handle:
Filter out hazardous property keys during traversal to prevent unauthorized modifications to the global object prototype.
Objects containing primitive values or mismatched types at the same key
How to Handle:
Overwrite the primitive value from obj1 with the incoming object or primitive value from obj2 directly.