↓Skip to main content
  1. LeetCode/

LeetCode 138: Copy List with Random Pointer

·2 mins· ·
LeetCode Medium Hash-Table Linked-List
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2022-10-29

  • Submissions: Wrong Answer → Time Limit Exceeded → Accepted ×2

Approach
#

random can point to a node not yet created, so make two passes (Linked List, Others):

  1. First pass: create a new node for each old one and store old -> new.
  2. Second pass: the new node’s next is d[old.next] and its random is d[old.random].

Seed the dictionary with None: None so None pointers need no special case.

My Attempts
#

Attempt 1 hard-coded the example’s answer, which of course failed. Attempt 2 used the dictionary approach but forgot cur = cur.next in the second loop (TLE); adding it passed.

Solution
#

class Solution:
    def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
        d = {None: None}
        cur = head
        while cur:
            d[cur] = Node(cur.val)
            cur = cur.next
        cur = head
        while cur:
            d[cur].next = d[cur.next]
            d[cur].random = d[cur.random]
            cur = cur.next
        return d[head]

Complexity
#

Time O(n), space O(n). Interleaving each new node after its old node gives O(1) extra space.

Mistakes to Avoid
#

  • The second loop must also advance cur.
  • Key the dictionary by node, not value (values can repeat).

Interview Explanation
#

random may point at a node not created yet, so one pass maps each old node to a new one and a second pass wires next and random, with None mapped to None to avoid special cases. Time and space O(n).

Related

LeetCode 105: Construct Binary Tree from Preorder and Inorder Traversal
·2 mins
LeetCode Medium Array Hash-Table Divide-and-Conquer Tree
LeetCode 105 note: the first pre-order value is the root, and its position in the in-order tells the left subtree’s size; look positions up in a dictionary for O(n)
LeetCode 143: Reorder List
·2 mins
LeetCode Medium Linked-List Two-Pointers Stack Recursion
LeetCode 143 note: find the middle, reverse the second half, and merge the two alternately, cutting the first half’s tail
LeetCode 208: Implement Trie (Prefix Tree)
·2 mins
LeetCode Medium Hash-Table String Design Trie
LeetCode 208 note: each node is a children dict plus an is_end flag; insert, search and startsWith all walk down character by character
LeetCode 424: Longest Repeating Character Replacement
·2 mins
LeetCode Medium Hash-Table String Sliding-Window
LeetCode 424 note: a variable sliding window where window length minus the top character count is the number of replacements; shrink when it exceeds k
LeetCode 981: Time Based Key-Value Store
·2 mins
LeetCode Medium Hash-Table String Binary-Search Design
LeetCode 981 note: store a (timestamp, value) list per key, with timestamps increasing; get binary searches the last timestamp <= the query
LeetCode 128: Longest Consecutive Sequence
·2 mins
LeetCode Medium Array Hash-Table Union-Find
LeetCode 128 note: put everything in a set and count upward only from values whose x - 1 is absent; each value is seen at most twice, O(n)