Leetcode 138: Copy List with Random Pointer

grid47
grid47
Exploring patterns and algorithms
Oct 24, 2024 6 min read

A glowing linked list with a soft, gentle pointer connecting to another, showing the copying process.
Solution to LeetCode 138: Copy List with Random Pointer Problem

Given a linked list where each node contains a value, a next pointer, and a random pointer (which can point to any node in the list or be null), create a deep copy of the list. The deep copy should consist of exactly n new nodes where each node has its value set to the value of its corresponding original node, and the next and random pointers of the new nodes should represent the same list state as the original. None of the pointers in the new list should point to nodes in the original list.
Problem
Approach
Steps
Complexity
Input: A linked list of nodes, each containing two pointers: a next pointer and a random pointer, which can point to any node or be null.
Example: head = [[5,null],[10,0],[15,4],[20,2],[25,1]]
Constraints:
• 0 <= n <= 1000
• -10^4 <= Node.val <= 10^4
• Node.random is null or points to some node in the linked list.
Output: Return the head of the deep copied linked list, where the copied list has the same values, next pointers, and random pointers as the original list.
Example: Output: [[5,null],[10,0],[15,4],[20,2],[25,1]]
Constraints:
• The copied list should have no shared nodes with the original list.
Goal: Create a deep copy of the linked list by ensuring that both the next and random pointers of the new nodes represent the same list structure as the original list.
Steps:
• 1. Iterate through the original list and create new nodes for each node in the original list.
• 2. Set the next pointer of each new node to match the corresponding next pointer in the original list.
• 3. Set the random pointer of each new node to match the corresponding random pointer in the original list.
• 4. Use a map or hash table to store mappings between the original nodes and their corresponding new nodes to handle random pointers efficiently.
Goal: The constraints ensure that the solution can handle linked lists with up to 1000 nodes while maintaining the correct structure for random pointers.
Steps:
• 0 <= n <= 1000
• -10^4 <= Node.val <= 10^4
• Node.random is null or points to some node in the linked list.
Assumptions:
• The input list contains nodes with valid random pointers that either point to a valid node or are null.
Input: head = [[5,null],[10,0],[15,4],[20,2],[25,1]]
Explanation: The original list contains five nodes with random pointers. The deep copy should have the same structure, where the next and random pointers of the new nodes match the original list.

Input: head = [[1,1],[2,1]]
Explanation: This example contains a two-node list where both nodes have random pointers pointing to each other. The deep copy should replicate the same structure.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus