NeetCode #960LC-2628MediumJavaScript
← Back to All Problems#960 · #2628 · JSON Deep Equal(完全相等的 JSON 对象)
📌 Problem Statement & Constraints
Given two objects
o1 and o2, return whether they are deeply equal: every key and value matches recursively, arrays must have equal length and order, and null must be distinguished from undefined.💡 Core Algorithmic Approaches
- Base case:
o1 === o2returns true, covering primitives and identical references. - If either side is not an object (including
null), return false. - Arrays and plain objects must match in kind: compare
Array.isArray(o1)withArray.isArray(o2). - The key sets must be identical (same size, and every key of
o1present ino2), then recurse on each key.
💻 Benchmark Python3 Implementation
var areDeeplyEqual = function(o1, o2) {
if (o1 === o2) return true; // primitives or the same reference
if (typeof o1 !== "object" || typeof o2 !== "object") return false;
if (o1 === null || o2 === null) return false;
if (Array.isArray(o1) !== Array.isArray(o2)) return false;
const k1 = Object.keys(o1);
const k2 = Object.keys(o2);
if (k1.length !== k2.length) return false;
for (const k of k1) {
if (!Object.prototype.hasOwnProperty.call(o2, k)) return false;
if (!areDeeplyEqual(o1[k], o2[k])) return false;
}
return true;
};⚡ Complexity Deep Dive
⏱️ Time Complexity
O(N): N is the total number of nodes in both objects.
💾 Space Complexity
O(D): D is the maximum nesting depth (recursion stack).
⚠️ Interview Pitfalls & Follow-ups
- Comparing with
JSON.stringify: differing key order would be misjudged as unequal, andundefinedversus a missing key cannot be distinguished. - Skipping the
nullcheck:typeof nullisobject, so execution would fall into the object branch and crash. - Not checking the array/object kind:
[]and{}both have empty key lists and would be wrongly considered equal. - Iterating keys of
o1only: equal lengths plus a presence check make this safe, but the explicithasOwnPropertyguard is clearer.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.