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
nextandrandompointers
π’ 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
.randomusing 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.