Explorer
JavaScript

Write a function `deepEqual(a, b)` that checks if two values are deeply equal (handles primitives, arrays, and plain objects).

Problem Statement

<p>Write a function <code>deepEqual(a, b)</code> that checks if two values are deeply equal (handles primitives, arrays, and plain objects).</p>

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

šŸ’” Hint 1: First handle primitive comparisons and null/undefined. šŸ’” Hint 2: For arrays, check length and recursively compare elements. šŸ’” Hint 3: For objects, check that both have the same keys and recursively compare values.

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

  1. Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
  2. Choose Core Mechanism: Use modern JavaScript patterns (first handle primitive comparisons and null/undefined).
  3. Implement Logic: Handle state and transformations efficiently (for arrays, check length and recursively compare elements).
  4. 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

Time Complexity O(N) where N is total properties and elements
Space Complexity O(D) recursive call stack depth

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.

Deep Equality Check

Hard

Write a function deepEqual(a, b) that checks if two values are deeply equal (handles primitives, arrays, and plain objects).

Example Scenarios
1Example 1
Input: deepEqual({ a: [1, 2] }, { a: [1, 2] })
Output: true
Explanation:

All nested values match deeply.

Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
[true,true,false,true]