Python coding

Clone a list with jump links

Each node of a singly linked list has val, next and jump, where jump points at any node of the same list (itself included) or is None. Write clone(head): return the first node of a deep copy, made of new nodes with the same values, whose next and jump point at the copy's own nodes in the same positions. Values can repeat. Leave the original list as you found it.

Aim for O(n) time; O(1) extra memory besides the copy is possible.

The tests call the provided run_clone(values, jumps): jumps[i] is the index of the node that node i jumps to, or null for none. It returns your copy's values and, for each copy node, the index its jump points at.

  • run_clone([7,13,11,10,1], [null,0,4,2,0]) → [[7,13,11,10,1],[null,0,4,2,0]]
  • run_clone([1,2], [1,1]) → [[1,2],[1,1]]
  • run_clone([], []) → [[],[]]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Make the copies first, then wire them: a dictionary from each original node to its copy turns every jump into one lookup. Key it by node, not by value: values repeat.

Hint 2

For O(1) extra memory, put each copy right after its original (A → A' → B → B'). Then the copy of node.jump is simply node.jump.next.

Hint 3

Finish by unzipping the two lists: each original takes back its old next, and the copies link to each other. The original must end up intact.

Solution and why it works
pythonO(n) · O(1) besides the copy
# --- your code ---
def clone(head: "Node | None") -> "Node | None":
    node = head
    while node is not None:              # 1. put each copy right after its original
        node.next = Node(node.val, node.next)
        node = node.next.next
    node = head
    while node is not None:              # 2. the copy of node.jump sits right after it
        if node.jump is not None:
            node.next.jump = node.jump.next
        node = node.next.next
    dummy = tail = Node()
    node = head
    while node is not None:              # 3. unzip: restore the original, chain the copies
        tail.next = node.next
        tail = tail.next
        node.next = tail.next
        node = node.next
    return dummy.next


# --- provided: do not edit ---
class Node:
    def __init__(self, val=0, next=None, jump=None):
        self.val = val
        self.next = next
        self.jump = jump


def run_clone(values: list[int], jumps: list[int | None]) -> list[list]:
    nodes = [Node(v) for v in values]
    for node, nxt in zip(nodes, nodes[1:]):
        node.next = nxt
    for node, j in zip(nodes, jumps):
        node.jump = None if j is None else nodes[j]
    before = [(n.val, n.next, n.jump) for n in nodes]
    node = clone(nodes[0] if nodes else None)
    if any(n.val != v or n.next is not nx or n.jump is not j for n, (v, nx, j) in zip(nodes, before)):
        raise ValueError("the original list was changed: leave it (or restore it) as it was")
    originals, copies = {id(n) for n in nodes}, []
    while node is not None:
        if id(node) in originals:
            raise ValueError("the copy reuses original nodes: create new ones")
        if len(copies) == len(nodes):
            raise ValueError("the copy has more nodes than the original: is there a cycle?")
        copies.append(node)
        node = node.next
    where = {id(n): i for i, n in enumerate(copies)}
    if any(n.jump is not None and id(n.jump) not in where for n in copies):
        raise ValueError("a jump in the copy points outside the copy")
    return [[n.val for n in copies], [None if n.jump is None else where[id(n.jump)] for n in copies]]

A jump can point at a node whose copy does not exist yet, so copy first and wire afterwards. A map from original to copy does it in O(n) time and memory. Interleaving needs only O(1) extra: with each copy right after its original, node.jump.next is the copy of the jump target, so one pass wires every jump and another unzips the lists, restoring the original. Traps: keying the map by value breaks with repeats, and finding each target by walking from the head is O(n²).