Implement Deep Clone
A structural copy of an object or array, arbitrary depth, no shared references — the recursive base case is 'not an object', and the branch that decides `[]` vs `{}` is what keeps arrays looking like arrays instead of an object with numeric keys.
The problem
Implement `deepClone(input)` returning a new value structurally identical to `input`, but where every nested object and array is a fresh copy — mutating the clone, or anything nested inside it, must never affect the original.
`input` can be a primitive, `null`, a plain object, or an array, nested to arbitrary depth. Primitives and `null` pass straight through, since they're already immutable by value and there's nothing to copy.
The approach
The base case comes first: anything that isn't an object — primitives, and `null`, since `typeof null === 'object'` needs its own explicit check — is returned as-is. The value itself is the copy.
`Array.isArray(input)` decides the shape of the container before any keys get copied: an array clone starts as `[]`, a plain object clone starts as `{}`. Getting this branch wrong is the classic bug — cloning an array into `{}` still copies every index across, but silently strips `Array.prototype` methods and `.length` semantics.
`for...in` walks every enumerable key, and `hasOwnProperty` filters out inherited ones so prototype-chain properties don't get copied along for the ride. Each value is cloned recursively before being assigned onto `result`, so nested objects and arrays get their own container at every level instead of sharing a reference with `input`.
The solution
function deepClone(input) {
if (input === null || typeof input !== 'object') {
return input;
}
const result = Array.isArray(input) ? [] : {};
for (const key in input) {
if (Object.prototype.hasOwnProperty.call(input, key)) {
result[key] = deepClone(input[key]);
}
}
return result;
}Time O(n)Space O(n)