Algorithm-Day33-Copy-List-with-Random-Pointer-lc-138
🧩 Problem Description
A linked list is given where each node has two pointers:
next
: points to the next noderandom
: can point to any node in the list or benull
Return a deep copy of the list.
Each node in the new list must have the same value and the same random
structure — but must be a new node, not shared.
💬 Example
1 | Input: |
💡 Approach 1: HashMap Mapping (Straightforward)
✨ Idea
- Traverse original list, and use a
HashMap<OldNode, NewNode>
to:- Store the mapping between original nodes and copied ones
- After building the copy, set the
next
andrandom
pointers
🔢 Java Code (Using HashMap)
1 | class Solution { |
- Time Complexity: O(n)
- Space Complexity: O(n) — due to the map
💡 Approach 2: Interleaving Nodes (O(1) Extra Space)
✨ Key Idea
- Clone each node and insert it right after the original:
A → A' → B → B' → ...
- Assign random pointers:
A'.random = A.random.next
- Detach the new list from the original
🔢 Java Code (No Extra Space)
1 | class Solution { |
- Time Complexity: O(n)
- Space Complexity: O(1)
✍️ Summary
- Understand how to maintain relationships with
.random
using either:- Hash map mapping (
O(n)
space) - Interleaved list strategy (
O(1)
space)
- Hash map mapping (
- This is a deep copy problem with pointer manipulation — commonly tested in interviews
Practice building clones of linked structures while preserving complex references. This is a great test of both logic and implementation skill.