Problem Description
Given two deeply nested JSON objects or arrays, return a new object that represents only the differences between them. For each key that exists in both objects, if their associated values differ, the output should contain that key with a value formatted as an array: [value from obj1, value from obj2]. If the differing values are themselves objects or arrays, the comparison should be performed recursively. Note that keys that have been added to or removed from one object (i.e. keys that do not exist in both) are ignored.
Key Insights
- Use recursion to traverse nested objects and arrays.
- Compare only keys that exist in both objects.
- When encountering two values of different types or unequal primitives, record the difference as [value from obj1, value from obj2].
- When both values are objects or arrays, recursively compute their differences and include them only if the resulting nested diff is non-empty.
- Arrays are treated like objects with indices as keys.
- The solution requires careful type checking and handling of recursive structures.
Space and Time Complexity
Time Complexity: O(n) in average, where n is the number of keys/elements in the common parts of the structures. Space Complexity: O(n) due to recursion and storage needed for the output differences.
Solution
We solve the problem using a recursive function that compares keys present in both input objects. For each common key:
- If both values are objects (or both are arrays), recursively compute their differences.
- If the recursive call returns a non-empty object, include that key in the result.
- If the two values are of different types or are primitives that differ, add the key with a difference array [value from obj1, value from obj2].
- Ignore keys that exist only in one object. This recursive approach naturally handles the deeply nested structure while ensuring only common keys with different values are captured.