Magicsheet logo

Differences Between Two Objects

Medium
100%
Updated 8/1/2025

Asked by 2 Companies

Topics

Differences Between Two Objects

What is this problem about?

The Differences Between Two Objects interview question is a common task in frontend or full-stack engineering interviews (often in JavaScript). Given two objects (or arrays), you need to return a new object that represents the deep differences between them. If a key exists in both and the values are different, you include the key with an array [oldValue, newValue]. If the values are identical, or if a key exists in only one object, it should be ignored. The comparison must be recursive for nested objects and arrays.

Why is this asked in interviews?

Google and Couchbase use this to test a candidate's mastery of Recursion and their understanding of data types. It evaluations your ability to traverse complex, nested structures and handle different edge cases (like comparing an object to an array or handling primitive vs. non-primitive types). This is a practical problem that mirrors tasks like state reconciliation in React or implementing "undo/redo" and "diffing" algorithms.

Algorithmic pattern used

This is a Recursive Traversal problem.

  1. Check the types: If the types of the two values are different, or if one is not an object/array, treat them as different.
  2. Iterate through the keys common to both objects.
  3. For each key, recursively call the diff function.
  4. If the recursive call returns a non-empty object (meaning there are differences inside), add that to your current diff object.
  5. If the values are primitives, compare them directly and store the [val1, val2] pair if they differ.

Example explanation

Object A: {"a": 1, "b": {"c": 2}} Object B: {"a": 1, "b": {"c": 3}, "d": 4}

  1. Key "a": Values are both 1. Ignore.
  2. Key "b": Both are objects. Recurse.
    • Key "c": 2 vs 3. Difference found! Return {"c": [2, 3]}.
  3. Key "d": Exists only in Object B. Ignore. Final Result: {"b": {"c": [2, 3]}}.

Common mistakes candidates make

  • Shallow Comparison: Forgetting to recurse into nested objects, resulting in comparing them as references rather than by content.
  • Type Mismatch: Not handling the case where a key contains an object in one version and a primitive in another.
  • Array vs Object: Failing to distinguish between arrays and plain objects (in JS, typeof [] is "object").
  • Missing/Extra Keys: Including keys that only exist in one of the two objects, when the problem usually specifies comparing only common keys.

Interview preparation tip

Understand the difference between Deep Equality and Deep Diffing. While they both use recursion, a diffing algorithm must build a new structure rather than just returning a boolean. Practice using Object.keys() and Array.isArray() to navigate dynamic JSON structures efficiently.

Similar Questions