Given two values obj1 and obj2, return a deepmerged value.
Values should be deepmerged according to these rules:
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 values1 <= JSON.stringify(obj1).length <= 5 * 1051 <= JSON.stringify(obj2).length <= 5 * 105When 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:
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:
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_objectTo 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:
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| Case | How to Handle |
|---|---|
| Null or undefined inputs for obj1 or obj2 | Check if either object is null, non-object, or primitive, and safely return the other object or a fallback. |
| Circular references within nested objects | Maintain a visited map or weak map to track already merged object references and prevent infinite recursion. |
| Merging arrays instead of replacing them | 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 | 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 | 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 | 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 | 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 | Overwrite the primitive value from obj1 with the incoming object or primitive value from obj2 directly. |