#138

Copy List with Random Pointer

Medium Interleave copies

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Each node has next and random pointers (random can point anywhere or be null). Return a deep copy of the list.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: deep-copy a list whose nodes also have a random pointer.

Why this works: put each copy right after its original. Then copy.random = original.random.next, and finally split the two lists.

Example: A(random C) → B → C

A → A' → B → B' → C → C'A'.random = A.random.next = C'split → A' → B' → C'

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Setting copy.random = original.random — that points into the original list, not the copy.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(1) extra.
Topic: Linked List
🎬 Episodes 40–45: video coming soon