How do you copy a list whose nodes have an extra pointer?
Each node also has jump, pointing at any node in the list or at None. The copy's jump pointers must point into the copy, not back into the original.
Map each old node to its new one in a dict, the way the hash-maps lesson remembers what it's seen. Then set the pointers in a second pass:
class JNode:
def __init__(self, val, next=None, jump=None):
self.val, self.next, self.jump = val, next, jump
def copy_with_jumps(head):
copies = {None: None}
node = head
while node is not None:
copies[node] = JNode(node.val)
node = node.next
node = head
while node is not None:
copies[node].next = copies[node.next]
copies[node].jump = copies[node.jump]
node = node.next
return copies[head]
The key None: None saves two if statements. copy.deepcopy does this too: its docs say it keeps a memo dictionary of the objects already copied, which is how it copies shared and cyclic references once. Then it recurses.
The follow-up after the dict is to do it in O(1) extra memory. Put each copy right after its original in the list, so old.next is old's copy. Then each copy's jump is old.jump.next. Then split the two lists apart:
def copy_interleaved(head):
node = head
# 1. a copy right after each node
while node is not None:
node.next = JNode(node.val, node.next)
node = node.next.next
node = head
# 2. the copy's jump is the copy of the original's jump
while node is not None:
node.next.jump = node.jump.next if node.jump is not None else None
node = node.next.next
new_head = head.next if head is not None else None
node = head
# 3. split the two lists apart
while node is not None:
twin = node.next
node.next = twin.next
twin.next = twin.next.next if twin.next is not None else None
node = node.next
return new_head
Here it is on three nodes, with A.jump at C and the copies marked with a ':
On 100,000 nodes with random jump pointers, both versions took about 45 ms. The dict version's peak was 14.83 MiB against 8.39 MiB for the copies alone, and the interleaving version's peak was the 8.39 MiB of copies.
On 1,000 nodes both copies checked out against the original, node by node, and the interleaving version left the original's next pointers as they were.