NeetCode #963LC-2700MediumJavaScript
← Back to All Problems#963 · #2700 · Differences Between Two Objects(两个对象之间的差异)
📌 Problem Statement & Constraints
Given two objects
obj1 and obj2, return their differences: a key present in only one object maps to [value, undefined] or [undefined, value]; when both sides hold plain objects at a key, recurse; otherwise a differing value maps to [v1, v2]. Return an empty object when there is no difference.💡 Core Algorithmic Approaches
- Fast path: if
JSON.stringify(obj1)equalsJSON.stringify(obj2), return an empty object. - Merge the key sets of both objects and compare key by key.
- If both sides hold plain (non-array) objects at a key, recurse and only record the branch when its result is non-empty.
- Otherwise, when
JSON.stringify(v1)differs fromJSON.stringify(v2), record[v1, v2], usingundefinedfor the missing side.
💻 Benchmark Python3 Implementation
var objDiff = function(obj1, obj2) {
if (JSON.stringify(obj1) === JSON.stringify(obj2)) return {};
const res = {};
const keys = new Set([...Object.keys(obj1), ...Object.keys(obj2)]);
for (const k of keys) {
const v1 = obj1[k];
const v2 = obj2[k];
const bothObj = v1 !== null && typeof v1 === "object" && !Array.isArray(v1)
&& v2 !== null && typeof v2 === "object" && !Array.isArray(v2);
if (bothObj) {
const sub = objDiff(v1, v2);
if (Object.keys(sub).length > 0) res[k] = sub; // keep only differing branches
} else if (JSON.stringify(v1) !== JSON.stringify(v2)) {
res[k] = [v1, v2];
}
}
return res;
};⚡ Complexity Deep Dive
⏱️ Time Complexity
O(N): N is the total number of nodes in both objects.
💾 Space Complexity
O(D): the recursion depth.
⚠️ Interview Pitfalls & Follow-ups
- Recursing into arrays as if they were plain objects: arrays should be compared as whole values.
- Recording empty sub-results: that produces a flood of meaningless empty objects; skip them.
- Using
nullfor a missing key: the problem requiresundefined. - Omitting the top-level fast path: correctness is unaffected, but an extra full traversal is performed.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.