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
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
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
- Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
- Choose Core Mechanism: Use modern JavaScript patterns (a shallow copy with object.assign or spread does not clone nested objects).
- Implement Logic: Handle state and transformations efficiently (recursively clone each property).
- 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
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.