Problem
Problem page: https://leetcode.com/problems/copy-list-with-random-pointer/
Topics: Hash Table, Linked List
Difficulty: Hard
Similar problems: (M) Clone Graph
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
Analysis
The tricky part is random. It's easy to copy a linked list by following next, but to make each new node's random point to the copy of the original node's random target, I need a way to find the copy of a given original node. I temporarily use the original node's next and the copy's random to keep track of the pair.
I save the original nodes in order in save_list, then follow next to make a new linked list, copying each node's label (its value) and leaving random alone. I walk both lists together, setting each original node's next to point to its copy and the copy's random to point back to the original node.
Next I walk the new list once, setting each copy's random to copy.random.random.next. The three steps take me to the original node, its original target, and the copy of that target. If the original node's random is null, I set the copy's random to null.
I need to fill save_list ahead of time and wait until I've set all the random pointers before using it to restore each original node's next to its original successor. If I restore each original node's next as I go through the loop that sets random, I'll get the wrong node when random points to an earlier node. I've already restored that node's next, so following next no longer gives me its copy.
The time complexity is O(n), and the extra space is O(n) too, all of it for save_list.
Code
1 | # Definition for singly-linked list with a random pointer. |
Article link: https://xnerv.wang/en/leetcode-copy-list-with-random-pointer/
