KatInterview

Clone a Linked List with Arbitrary Jump Links

Linked ListsAuto-graded · 17 test cases
MediumAuto-gradedLinked Listslinked-listhash-mapdeep-copy

Last updated

Build an independent duplicate of a linked list whose nodes carry both a next link and an arbitrary jump link, using a serialized list-of-records format.

Clone a Linked List with Jump Links

A singly linked list has n nodes. Each node stores an integer val, a next link to the following node (or None at the tail), and a jump link that points to any node in the same list (possibly itself) or is None.

Your task is to build a deep copy of such a list: n brand-new nodes, where the copy of each node has the same value, and its next and jump links point to the copies of the nodes that the original links pointed to. A None link stays None. No link in the copy may point into the original list, and the original must not be changed.

Serialized format

The judge calls your function with the list in serialized form, and expects the serialized form of your copy back.

  • The input records is a list of n entries, one per node, in order from head to tail.
  • Entry i is [val, jump_index], where val is the value of node i, and jump_index is the 0-based position of the node that node i's jump link points to, or None if the jump link is None.
  • The next link of node i goes to node i + 1; the last node's next is None.

Your function should:

  1. Build real linked nodes from records.
  2. Create a deep copy of that list.
  3. Serialize the copy by walking its own next links from its head, giving each node [val, jump_index] where jump_index is the position (in the copy) of the node its jump link targets, or None.

Return the resulting list of records. If records is empty, return an empty list.

Because the copy mirrors the original exactly, the returned list has the same content as the input when the copy is built correctly.

Constraints

  • 0 <= n <= 10^4
  • -10^4 <= val <= 10^4
  • jump_index is None or an integer in [0, n - 1].
  • Several nodes may share the same value; nodes are distinguished by identity, not by value.
  • A node's jump link may point to itself, backward, or forward.

Examples

Example 1

Input: clone_jump_list([[7, None], [13, 0], [11, 4], [10, 2], [1, 0]])

Output: [[7, None], [13, 0], [11, 4], [10, 2], [1, 0]]

Example 2

Input: clone_jump_list([[1, 1], [2, 1]])

Output: [[1, 1], [2, 1]]

Hints

Hint 1

When you copy a node, its jump target may not have been copied yet. Think about how to separate creating nodes from connecting them.

Hint 2

Use a dictionary keyed by the original node object (identity, not value) that maps to its new copy. Create all copies first, then wire next and jump in a second pass.

Hint 3

Treat None specially: looking up None should yield None. For serialization, build a reverse map from each copied node to its position as you walk the copy.