Top 150 InterviewЛегко

Copy List With Random Pointer

Detailed guide and Python implementation for the 'Copy List With Random Pointer' problem.

Постановка задачи

Легко

A linked list of length n is given such that each node contains an additional random pointer, which could point to any node in the list, or null.

Construct a deep copy of the list. The deep copy should consist of exactly n brand new nodes, where each new node has its value set to the value of its corresponding original node. Both the next and random pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state.

The list is represented as a list of pairs [val, random_index] where random_index is the index of the node the random pointer points to, or -1 if it points to null. Implement a function copyRandomList(head: list) -> list that returns the deep copy in the same format.

Ограничения
  • 0 <= n <= 1000
  • -10000 <= Node.val <= 10000
  • Node.random is null or points to some node in the linked list

Примеры

Example 1
Input
[[7,-1],[13,0],[11,4],[10,2],[1,0]]
Output
[[7,-1],[13,0],[11,4],[10,2],[1,0]]
Explanation

The deep copy has the same structure. Node 0 (val=7) has random=null, Node 1 (val=13) has random pointing to Node 0, etc.

Example 2
Input
[[1,1],[2,1]]
Output
[[1,1],[2,1]]
Explanation

Node 0 (val=1) has random pointing to Node 1. Node 1 (val=2) has random pointing to Node 1 (itself).

Example 3
Input
[[3,-1],[3,0],[3,-1]]
Output
[[3,-1],[3,0],[3,-1]]
Explanation

Three nodes all with value 3. Node 1's random points to Node 0.

Need a Hint?
Consider using Linked List-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Готовы решить?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Открыть в редакторе
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

Рекомендуемые ресурсы Python

Расширьте свои знания с помощью соответствующих интерактивных руководств, шпаргалок и сравнений кода.