15 · Linked Lists

#138 Copy List with Random Pointer

Mediumsolve on LeetCode ↗

frequently reported atMetaAmazonNVIDIAMicrosoftBloombergAdobe

the problem

In plain words

Each node has next and random (pointing to any node or null). Return a deep copy: brand-new nodes whose next and random mirror the original structure.

in head = [[7,null],[13,0],[11,4],[10,2],[1,0]]

out [[7,null],[13,0],[11,4],[10,2],[1,0]]

Each pair is [val, index of random]. The output is a copy built from new nodes.

in head = [[1,1],[2,1]]

out [[1,1],[2,1]]

in head = [[3,null],[3,0],[3,null]]

out [[3,null],[3,0],[3,null]]

  • 0 ≤ n ≤ 1000
  • -10⁴ ≤ Node.val ≤ 10⁴
  • random is null or points to a node in the list

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #133
      Clone Graph
      Mediumin Graphs
    2. #1
      Two Sum
      Easyin Hashing