KatInterview

Clone a List with Index-Based Cross References

Arrays & HashingAuto-graded · 18 test cases
EasyAuto-gradedArrays & Hashingarraysdeep-copylist-manipulation

Last updated

Tests your ability to perform a deep copy of a nested list structure while preserving integer-indexed references between elements.

Problem Statement

You receive a list where each element is a two-item array [value, reference_index]. The value is an integer, and reference_index is either an integer pointing to a position in the list or null.

Your task is to create a deep copy of this list. The copy must contain entirely new nested arrays, not references to the original arrays. However, the structure and all values must be identical.

Input Format

A list of arrays, where each array contains:

  • value: an integer
  • reference_index: an integer index (0-based) pointing to another element in the list, or null

Output Format

A new list with the same structure, where all nested arrays are newly created objects.

Constraints

  • 0 <= n <= 1000 where n is the length of the list
  • -10000 <= value <= 10000
  • reference_index is either null or a valid index 0 <= reference_index < n

Edge Cases

  • An empty list returns an empty list
  • A single element with reference_index as null or 0 (pointing to itself)
  • Multiple elements with the same value but different reference indices

Examples

Example 1

Input: clone_reference_list([[7, None], [13, 0], [11, 4], [10, 2], [1, 0]])

Output: [[7, None], [13, 0], [11, 4], [10, 2], [1, 0]]

Example 2

Input: clone_reference_list([])

Output: []

Example 3

Input: clone_reference_list([[1, None]])

Output: [[1, None]]

Example 4

Input: clone_reference_list([[5, 0], [5, 1], [5, None]])

Output: [[5, 0], [5, 1], [5, None]]

Hints

Hint 1

Think about what 'deep copy' means for nested structures—you need to create new inner arrays, not just copy references.

Hint 2

Python's list slicing creates a shallow copy of the outer list, but what about the inner arrays?

Hint 3

Consider using list comprehension to create new arrays element by element.