Copy List with Random Pointer
You get a linked list where every node has, besides next, a link called random to any node of the same list or to none. Make a full copy: new nodes with the same values, and every link of the copy goes to a new node, never to an old one. Our example: 3 → 8 → 5 → 1, random 3 → 5, 8 → 3, 5 → none, 1 → 1 (itself).
- input
head: the head of a linked list, ornullfor an empty one; each node also hasrandom, a pointer to any node of the list ornull. The tests write the list as LeetCode does:[val, random’s index]per node,nullfor no random.- returns
- The head of a deep copy: new nodes with the same values, whose
nextandrandompoint to the copy’s own nodes as the input’s point to the input’s. No node of the copy may be a node of the input, and the input must stay as it came. - constraints
- 0 ≤ the number of nodes ≤ 500
- −10⁴ ≤ Node.val ≤ 10⁴
- random is null or the index of a node of the list
- examples
- Open a test in the tests panel: it shows the input and the expected answer.
/**
* // Definition for a _Node.
* function _Node(val, next, random) {
* this.val = val;
* this.next = next;
* this.random = random;
* };
*/
/**
* @param {_Node} head
* @return {_Node}
*/
function copyRandomList(head) {
}
Ctrl ↵
format
reset
saved in this browser
Stuck?
See the solution run step by step on our example, then why it works and its complexity.
Next: more hash map problems
- 1Two SumEasysolve
- 217Contains DuplicateEasysolve
- 242Valid AnagramEasysolve
- 169Majority ElementEasysolve
- 383Ransom NoteEasysolve
- 205Isomorphic StringsEasysolve
- 290Word PatternEasysolve
- 219Contains Duplicate IIEasysolve
- 49Group AnagramsMediumsolve
- 128Longest Consecutive SequenceMediumsolve
- 36Valid SudokuMediumsolve
- 149Max Points on a LineHardsolve
The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.