Write a function `deepEqual(a, b)` that checks if two values are deeply equal (handles primitives, arrays, and plain objects).
Problem Statement
Examples
Input: deepEqual({ a: [1, 2] }, { a: [1, 2] })
Output: true
Explanation: All nested values match deeply.
Complexity
Time Complexity: O(N)
Space Complexity: O(D)
Hints
Editorial & Approach
Problem Overview & Intuition
To solve Deep Equality Check, we consider the execution characteristics of JavaScript engines. Write a function `deepEqual(a, b)` that checks if two values are deeply equal (handles primitives, arrays, and plain objects). By utilizing idiomatic language constructs and clean algorithmic principles, we can accomplish this with optimal time and memory usage.
Step-by-Step Approach
- Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
- Choose Core Mechanism: Use modern JavaScript patterns (first handle primitive comparisons and null/undefined).
- Implement Logic: Handle state and transformations efficiently (for arrays, check length and recursively compare elements).
- Return Result: Ensure proper return format and preserve caller context if applicable.
Optimal Implementation (JavaScript)
function deepEqual(a, b) {
if (a === b) return true;
if (a === null || b === null || typeof a !== "object" || typeof b !== "object") return false;
if (Array.isArray(a) !== Array.isArray(b)) return false;
const keysA = Object.keys(a);
const keysB = Object.keys(b);
if (keysA.length !== keysB.length) return false;
return keysA.every(key => deepEqual(a[key], b[key]));
}
Complexity Analysis
Edge Cases & Corner Traps Handled
- Empty or boundary inputs (empty arrays, strings, zero length).
- Type checks and unexpected values (e.g.
null,undefined, negative numbers). - Closure preservation and memory isolation between separate invocations.