Duplicate a Nested Structure With Cycles and Shared Parts
Trees & GraphsAuto-graded · 19 test casesLast 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Copying a nested structure is a graph copy. The same container can be reachable from several places, and a container can even contain itself. A naive recursive copy would duplicate shared parts and loop forever on cycles.
The solution keeps a memo table that maps id(original) to its clone:
- Atoms (
None, bool, numbers, strings, bytes) are immutable, so they are returned directly. - For a list, dict or set, check the memo first. If the container was already seen, return the existing clone. Otherwise create an empty shell of the same type, store it in the memo immediately, and push
(original, shell)onto an explicit stack to be filled later. - Loop: pop a pair from the stack and fill the shell. Each child goes through the same memo-aware helper, so children that are already cloned resolve to the same clone, and new containers get their own shell and a stack entry.
- Other types (tuples, dates, regex objects, user objects) are delegated to
copy.deepcopy, passing our memo so identity is still shared with the rest of the clone.
Why it is correct
- Shared references stay shared. Every container is cloned at most once, and every later encounter returns
memo[id(obj)]. - Cycles close correctly. The shell is registered in the memo before its children are processed, so a child that points back to an ancestor gets the ancestor's clone.
- Deep inputs are safe. The traversal uses a heap-allocated stack rather than the call stack, so nesting depth is limited only by memory.
- Order is preserved. Lists are extended in order and dicts are filled in their insertion order, so equal structures compare equal.
- The original is untouched. We only read from it.
Complexity
- Time: O(N) for N nodes plus entries, since each container is expanded once.
- Space: O(N) for the memo, the stack and the clone.
Reference solution
import copy
def clone_nested(value):
memo = {}
work = []
def clone_node(obj):
if obj is None or isinstance(obj, (bool, int, float, complex, str, bytes)):
return obj
oid = id(obj)
if oid in memo:
return memo[oid]
if type(obj) is list:
result = []
memo[oid] = result
work.append((obj, result))
return result
if type(obj) is dict:
result = {}
memo[oid] = result
work.append((obj, result))
return result
if type(obj) is set:
result = set()
memo[oid] = result
work.append((obj, result))
return result
# Other types (tuples, dates, compiled regexes, custom objects):
# defer to the standard library, sharing our memo.
return copy.deepcopy(obj, memo)
result = clone_node(value)
while work:
source, target = work.pop()
if type(source) is list:
target.extend(clone_node(item) for item in source)
elif type(source) is dict:
for key, item in source.items():
target[clone_node(key)] = clone_node(item)
else: # set
target.update(clone_node(item) for item in source)
return result