FrontendInterviews.dev

Loading problem…

34. Deep Clone

Easy•
Acceptance: 95.65%
•
🔓3/3 Pro unlocks today

Implement deepClone for values composed of primitives, arrays, and plain objects.

Requirements

1) Supported input scope

  • Primitive values (number, string, boolean, null, undefined)
  • Arrays (possibly nested)
  • Plain objects (possibly nested)

2) Clone behavior

  • Return a structurally equal deep copy.
  • Nested objects/arrays must not share references with the original.
  • Modifying the clone must not mutate original nested values.

3) Edge cases

  • Empty objects/arrays should clone correctly.
  • Primitive input should be returned as-is.

4) Assumption (base version)

  • You may assume input does not contain circular references.
  • Special objects (Map/Set/Date/RegExp) are out of scope in this base problem.

Examples

const original = { a: 1, b: { c: 2 } }
const cloned = deepClone(original)
cloned.b.c = 99

// original.b.c is still 2
const arr = [1, [2, 3], { x: 4 }]
const cloned = deepClone(arr)
cloned[1][0] = 9

// arr[1][0] is still 2

Constraints

  • Recursively clone arrays and plain objects.
  • Return primitive values directly.
  • Do not mutate the input.
  • Assume no circular references for this base version.