Clone a LL with random and next pointer

Linked-List FAQs (Hard) Hard

Given the head of a special linked list of n nodes where each node contains an additional pointer called 'random' which can point to any node in the list or null.


Construct a deep copy of the linked list where,

  • n new nodes are created with corresponding values as original linked list.
  • The random pointers point to the corresponding new nodes as per their arrangement in the original list.
  • Return the head of the newly constructed linked list.


Note: For custom input, a n x 2 matrix is taken with each row having 2 values:[ val, random_index] where,

  • val: an integer representing ListNode.val
  • random_index: index of the node (0 - n-1) that the random pointer points to, otherwise -1.

Examples:

Input: [[1, -1], [2, 0], [3, 4], [4, 1], [5, 2]]

Output: 1 2 3 4 5, true

Explanation: All the nodes in the new list have same corresponding values as original nodes.

All the random pointers point to their corresponding nodes in the new list.

'true' represents that the nodes and references were created new.

Input: [[5, -1], [3, -1], [2, 1], [1, 1]]

Output: 5 3 2 1, true

Explanation: All the nodes in the new list have same corresponding values as original nodes.

All the random pointers point to their corresponding nodes in the new list.

'true' represents that the nodes and references were created new.

Input: [[-1, -1], [-2, -1], [-3, -1], [10, -1]]

Constraints

  • n == number of nodes in the linked list.
  • 1 <= n <= 105
  • -104 <= ListNode.val <= 104
  • 0 <= random_index < n or random_index == -1.

Hints

  • A brute-force approach would involve: Creating a copy of each node (O(n) space). Using a HashMap (O(n) space) to store old node → new node mapping. Fixing the random pointers in a second pass (O(n)).
  • To achieve O(n) time and O(1) space, use: Interleaving Technique: Clone nodes in-place without extra space. Restoring the random pointers using the interleaved structure. Separating the new list from the old one

Company Tags

Teladoc Health Databricks GE Healthcare Zoho Docker Reddit Robinhood Stripe ARM Morgan Stanley Bain & Company Zomato Unity Technologies Etsy eBay Dropbox IBM Cerner Epic Games Airbnb Nutanix Shopify PwC Johnson & Johnson Instacart Google Microsoft Amazon Meta Apple Netflix Adobe