Explorer
JavaScript

Write a function `deepClone(obj)` that creates a deep copy of a plain object (handles nested objects and arrays, not functions/dates/etc).

Problem Statement

<p>Write a function <code>deepClone(obj)</code> that creates a deep copy of a plain object (handles nested objects and arrays, not functions/dates/etc).</p>

Examples

Input: obj = { a: 1, b: { c: 2 } }

Output: { a: 1, b: { c: 2 } }

Explanation: Nested objects are cloned so mutating the clone does not affect original.

Complexity

Time Complexity: O(N)

Space Complexity: O(D)

Hints

šŸ’” Hint 1: A shallow copy with Object.assign or spread does not clone nested objects. šŸ’” Hint 2: Recursively clone each property. šŸ’” Hint 3: Use JSON.parse(JSON.stringify(obj)) for simple cases, or recursion for more control.

Editorial & Approach

Problem Overview & Intuition

To solve Deep Clone Object, we consider the execution characteristics of JavaScript engines. Write a function `deepClone(obj)` that creates a deep copy of a plain object (handles nested objects and arrays, not functions/dates/etc). 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 (a shallow copy with object.assign or spread does not clone nested objects).
  3. Implement Logic: Handle state and transformations efficiently (recursively clone each property).
  4. Return Result: Ensure proper return format and preserve caller context if applicable.

Optimal Implementation (JavaScript)

function deepClone(obj) {
  if (obj === null || typeof obj !== "object") return obj;
  if (Array.isArray(obj)) return obj.map(deepClone);
  const clone = {};
  for (const key of Object.keys(obj)) {
    clone[key] = deepClone(obj[key]);
  }
  return clone;
}

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 Clone Object

Medium

Write a function deepClone(obj) that creates a deep copy of a plain object (handles nested objects and arrays, not functions/dates/etc).

Example Scenarios
1Example 1
Input: obj = { a: 1, b: { c: 2 } }
Output: { a: 1, b: { c: 2 } }
Explanation:

Nested objects are cloned so mutating the clone does not affect original.

Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
{"origC":99,"clonedC":2,"origD":[3,4,5],"clonedD":[3,4]}