Skip to main content

Deep Merge of Two Objects - Solution & Explanation

MediumPremiumFree on FleetCode4 min readAsked at: Valve
Practice this problem

Problem Statement

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

Approach Overview

Problem Overview: You receive two JSON-like objects and must merge them deeply. If a key exists in both objects and both values are objects, merge them recursively. Otherwise, the value from the second object overrides the first.

Approach 1: Recursive DFS Merge (O(n) time, O(d) space)

The natural way to solve deep merge is recursion. Iterate through every key in the second object. If the same key exists in the first object and both values are objects, call the merge function recursively on those nested objects. Otherwise, directly assign the value from the second object into the first. This works because nested structures form a tree, and recursion performs a depth-first traversal through every nested property. Each property is processed exactly once, giving O(n) time where n is the total number of keys across the structure. The recursion stack consumes O(d) space where d is the maximum nesting depth.

The key detail is correctly detecting whether a value should be merged or replaced. Only merge when both values are objects (including arrays in JavaScript). If one side is a primitive, the second object wins. This mirrors how many real-world configuration merge utilities work. The approach relies heavily on recursive traversal patterns commonly seen in recursion and depth-first search problems.

Approach 2: Iterative Stack-Based Merge (O(n) time, O(n) space)

An alternative implementation replaces recursion with an explicit stack. Push pairs of objects that still need merging. While the stack is not empty, pop a pair and iterate through the keys of the second object. When both values are objects, push the nested pair onto the stack for later processing. Otherwise assign the value from the second object. This approach performs the same operations as the recursive version but avoids recursion depth limits.

The iterative solution still processes each key once, so the runtime remains O(n). However, the stack can grow up to O(n) in the worst case if many nested objects must be processed. This technique is useful when working with very deeply nested data where recursion could overflow the call stack.

Recommended for interviews: The recursive DFS merge is the expected solution. It is concise, mirrors the hierarchical structure of nested objects, and demonstrates strong understanding of hash map style key iteration and recursion. Mentioning the iterative stack alternative shows deeper understanding of recursion tradeoffs and stack limits.

Solution

Code

TypeScript

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Recursive DFS MergeO(n)O(d)Preferred solution. Clean recursive traversal of nested objects.
Iterative Stack-Based MergeO(n)O(n)Useful when avoiding recursion depth limits in deeply nested structures.

Video Solution

Merge Two Sorted Lists - Leetcode 21 - Python • NeetCode • 438,617 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Deep Merge of Two Objects easy or hard?
Deep Merge of Two Objects is typically considered a medium-level problem. The challenge comes from correctly handling nested structures and deciding when to recursively merge versus overwrite values.
Deep Merge of Two Objects Python/Java solution
The same idea works in Python and Java by recursively merging dictionaries or maps. For each key in the second structure, check whether both values are maps/dictionaries. If they are, recursively merge them; otherwise overwrite the value. The complexity remains O(n).
How to solve Deep Merge of Two Objects in O(n)?
Iterate through the keys of the second object and merge them into the first. If both values for a key are objects, recursively call the merge function on those nested objects. Otherwise overwrite the value in the first object. Because each property is processed once, the runtime remains O(n).
What is the best approach for Deep Merge of Two Objects?
The recursive DFS merge approach is considered the best solution. It recursively merges nested objects when the same key exists in both inputs and replaces values otherwise. This approach processes every key once, resulting in O(n) time complexity and O(d) space complexity where d is the nesting depth.
Is Deep Merge of Two Objects asked at Google/Amazon/Meta?
Deep object manipulation problems appear in frontend and JavaScript-heavy interviews at companies like Google, Amazon, and Meta. Variations often test recursion, object traversal, and JSON data processing, especially for frontend or full‑stack roles.
What data structure is used in Deep Merge of Two Objects?
The solution primarily uses JavaScript objects acting as hash maps for key-value storage. The algorithm traverses nested objects using recursion or a stack, similar to depth-first search on a tree-like structure.
What is the time complexity of Deep Merge of Two Objects?
The time complexity is O(n), where n is the total number of properties across all nested objects. Each key is visited once during the merge process. The recursion stack adds O(d) auxiliary space where d represents the maximum depth of nested objects.

Ready to solve this problem?

Practice Deep Merge of Two Objects with our built-in code editor and test cases.

Practice on FleetCode