LinkedList
Data Structures
Random Pointer
Algorithm
Coding Interview

Duplicate a LinkedList with a pointer to a random node apart from the next node

Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms

Introduction

Duplicating a linked list that contains an additional random pointer (apart from the typical next pointer) is a common problem in algorithms, often appearing in technical interviews and coding challenges. Each node in such a linked list not only points to the next node, but also has a random pointer that can point to any node in the list, or it can be null. This adds complexity to the task of duplicating the list accurately with all connections preserved.

In this article, we explore a method to duplicate such a linked list using hash maps to maintain the complex structure without altering the original list.

Problem Definition

Given a linked list where each node contains three pointers:

  1. Next pointer: Points to the next node in the sequence.
  2. Random pointer: Can point to any node in the list or be null.
  3. Value: Holds data specific to each node.

The goal is to create a deep copy of this linked list, such that both the next and random pointers in the deep copy point to the corresponding nodes in the new list.

Conceptual Approach

Here's how you can undertake the duplication in an efficient manner:

  1. Iterate through the original list and clone each node. Use a hash map to store the mapping from the original nodes to their corresponding cloned nodes.
  2. Maintain the mappings for proper linking. In a second pass, update the next and random pointers for each node in the cloned list using the created mappings.
  3. Return the head of the cloned list.

Detailed Explanation

The entire process can be outlined in the following steps:

Step 1: Copy Nodes and Map Original to Cloned Nodes

First, traverse the original linked list and create the clone nodes. Utilize a hash map where keys are the original nodes and values are the newly cloned nodes:

  • Complex Data Structures: Used in software systems where data sharing with complex linking is prevalent.
  • Machine Learning and AI: In duplication tasks for maintaining data integrity during transformations.

Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms