Clone a Linked List with Random Pointers

Given a linked list where each node contains two pointers: one pointing to the next node and another random pointer that can point to any node within the list (or be null), your task is to create a deep copy of this linked list and return the head of the copied list.

Explanation:

A deep copy of a linked list means creating entirely new nodes for each node in the original list without retaining any references to the nodes of the original linked list.

Input:

The first line of input contains an integer ‘T’, representing the number of test cases. Each test case consists of a single line containing elements of the linked list with random pointers, represented by node-value and random-index pairs separated by a space.

Each node is described as: Value RandomIndex, where Value is an integer denoting the node value, and RandomIndex is the index of the node where the random pointer is directed to, or -1 if it does not point to any node.

Output:
For each test case, output “True” if the linked list is successfully cloned, otherwise “False”. Each result should be on a separate line.

Example:

Input:
1
1 2 2 0 3 -1
Output:
True

Constraints:

  • 1 ≤ T ≤ 10
  • 0 ≤ N ≤ 5 * 104
  • -105 ≤ data ≤ 105 and data ≠ -1
  • -1 ≤ random_index < N
Note:
You do not need to print anything; the output handling is already taken care of. Please implement the function to create a deep copy of the linked list.
AnswerBot
4mo

Create a deep copy of a linked list with random pointers.

  • Iterate through the original linked list and create a new node for each node in the list.

  • Store the mapping of original nodes to new nodes in a ...read more

Help your peers!
Select
Add answer anonymously...

Top Data Scientist Interview Questions Asked at Bajaj Finserv

Q. What detailed questions do you have about machine learning models?
Q. What is cross validation?
Q. With 2 dependent and 6 independent variables available, which machine learning a...read more
Data Scientist Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2025 Info Edge (India) Ltd.

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits