KatInterview

Duplicate a Nested Structure With Cycles and Shared Parts

Trees & GraphsAuto-graded · 19 test cases
MediumAuto-gradedTrees & Graphsdeep-copygraph-traversalmemoization

Last updated

Build an independent deep copy of a nested container structure, preserving shared references and cycles, using a memo table and an explicit stack.

Write a function clone_nested(value) that returns a fully independent deep copy of an arbitrarily nested Python value. Do not use JSON serialization or third-party libraries. Calling copy.deepcopy on the whole input is also not the intended solution. You may use the standard library for leaf-level helper cases.

Behavior

  • Atoms (None, booleans, numbers, strings, bytes) are returned as they are.
  • Lists, dicts and sets must be rebuilt as new containers of the same type. Their contents must be cloned recursively. Dict keys and set members are cloned too, when they are not atoms.
  • Other objects (for example tuples, dates, compiled regular expressions, user-defined class instances) must also come back as independent copies of the same type and equal in content.
  • Shared references stay shared. If two places in the input refer to the same container object, the corresponding two places in the output must refer to one single cloned container. This is not a pair of equal copies.
  • Cycles are supported. If a container directly or indirectly contains itself, the clone must contain itself in the same way. The function must terminate.
  • Nothing in the result may be the same mutable object as in the input. Mutating the clone must never affect the original, and vice versa.
  • The input must not be modified.
  • The result must compare equal to the input for acyclic data, with the same element order for lists and the same insertion order for dicts.

Input and output

  • value: any nested Python value as described above.
  • Returns: a deep copy of value.

Constraints

  • The structure can be very deep (for example, a chain of 100,000 nested lists), so a plain recursive solution may exceed the recursion limit. Aim for an approach whose depth is limited only by memory.
  • The total number of distinct nodes is at most about 10^5.
  • Each distinct container in the input should be cloned at most once.
  • Functions, if present, are kept as they are (they are not copied).

Examples

Example 1

Input: clone_nested({'name': 'A', 'meta': {'scores': [3, 5], 'active': True}})

Output: {'name': 'A', 'meta': {'scores': [3, 5], 'active': True}}

Example 2

Input: clone_nested([1, {'x': [2, 3]}, None])

Output: [1, {'x': [2, 3]}, None]

Example 3

Input: clone_nested(42)

Output: 42

Hints

Hint 1

Treat the data as a graph, not a tree. Keep a dictionary that maps the identity (`id`) of each original container to its clone.

Hint 2

Create the empty clone first and register it in the memo before looking at its children. Then a child that points back to an ancestor finds the ancestor's clone in the memo, which closes the cycle and keeps shared parts shared.

Hint 3

Replace recursion with an explicit stack of (original, clone) pairs still to be filled. Pop a pair, clone each child through the memo-aware helper, and write the results into the clone.