Diwali Offer!Flat 20% OFF
Enroll Now
PrakalpanaLive online tech training

78. Copy List with Random Pointer

MediumDay 23 of 60Linked List

Each node of a linked list has a next pointer and an extra random pointer that can point to any node in the list or be null. Build a deep copy: a brand new list of new nodes with the same values, where every copied next and random points to copied nodes, never to the original ones. Return the head of the copy and leave the original list unchanged. Tests describe a list as [val, randomIndex] pairs, where randomIndex is the position the random pointer targets or null.

Example 1
Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
Output: [[7,null],[13,0],[11,4],[10,2],[1,0]]
The copy has the same shape, but every node in it is new.
Example 2
Input: head = [[1,1],[2,1]]
Output: [[1,1],[2,1]]
Constraints
  • 0 <= n <= 1000
  • -10^4 <= Node.val <= 10^4
  • `Node.random` is null or points to a node in the list
Hints
Frequently asked at: Amazon, Microsoft, Meta, Bloomberg
Ctrl + Enter runs the examples

Not sure what to learn next?

A 1-on-1 session with an industry mentor and a roadmap built for you. How it works

  1. 1Discuss your goals
  2. 2Get a personal plan
  3. 3Start learning
Book for β‚Ή200/ 30 min