Differences Between Two Objects - Problem

Write a function that accepts two deeply nested objects or arrays obj1 and obj2 and returns a new object representing their differences.

The function should compare the properties of the two objects and identify any changes. The returned object should only contain keys where the value is different from obj1 to obj2. For each changed key, the value should be represented as an array [obj1 value, obj2 value].

Important: Keys that exist in one object but not in the other should not be included in the returned object. The end result should be a deeply nested object where each leaf value is a difference array.

When comparing two arrays, the indices of the arrays are considered to be their keys. You may assume that both objects are the output of JSON.parse.

Input & Output

Example 1 — Basic Object Differences
$ Input: obj1 = {"a": 5, "b": 1}, obj2 = {"a": 1, "b": 1}
Output: {"a": [5, 1]}
💡 Note: Key 'a' has different values (5 vs 1), key 'b' has same values (1 vs 1) so not included
Example 2 — Nested Object Changes
$ Input: obj1 = {"a": {"b": 2}}, obj2 = {"a": {"b": 3}}
Output: {"a": {"b": [2, 3]}}
💡 Note: Nested property a.b differs: 2 vs 3, so result maintains nested structure
Example 3 — Array Index Comparison
$ Input: obj1 = [1, 2, 3], obj2 = [1, 3, 3]
Output: {"1": [2, 3]}
💡 Note: Array index 1 differs (2 vs 3), indices 0 and 2 are same so not included

Constraints

  • Objects are valid JSON structures
  • Nested depth ≤ 100 levels
  • Total properties ≤ 104

Visualization

Tap to expand
Differences Between Two Objects Optimized Depth-First Traversal INPUT obj1 { "a": 5, "b": 1 } obj2 { "a": 1, "b": 1 } Compare keys: "a", "b" "a" "b" DIFF SAME ALGORITHM STEPS 1 Get Common Keys Find keys in both objects 2 Compare Values Check if values differ 3 Recurse if Objects DFS for nested structures 4 Build Result Store [val1, val2] for diffs Comparison Process Key obj1 obj2 Diff? "a" 5 1 YES "b" 1 1 NO FINAL RESULT Differences Object { "a": [5, 1] } Format Explained [obj1 value, obj2 value] [5, 1] means 5 --> 1 Output: {"a": [5, 1]} OK - Only changed keys Key Insight: Only include keys that exist in BOTH objects and have DIFFERENT values. Use DFS to handle nested objects/arrays. Each difference stored as [oldVal, newVal] array. TutorialsPoint - Differences Between Two Objects | Optimized Depth-First Traversal
Asked in
Facebook 35 Google 28 Netflix 22
23.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen