Bird
Raised Fist0
DSA Pythonprogramming~20 mins

Clone Linked List with Random Pointer in DSA Python - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Random Pointer Cloning Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of cloning a linked list with random pointers
What is the printed output of the cloned linked list's values and their random pointers after running the given code?
DSA Python
class Node:
    def __init__(self, val, next=None, random=None):
        self.val = val
        self.next = next
        self.random = random

def print_list(head):
    result = []
    current = head
    while current:
        random_val = current.random.val if current.random else None
        result.append(f"{current.val}({random_val})")
        current = current.next
    print(' -> '.join(result) + ' -> None')

def clone_linked_list(head):
    if not head:
        return None

    # Step 1: Insert cloned nodes
    current = head
    while current:
        new_node = Node(current.val, current.next)
        current.next = new_node
        current = new_node.next

    # Step 2: Copy random pointers
    current = head
    while current:
        if current.random:
            current.next.random = current.random.next
        current = current.next.next

    # Step 3: Separate lists
    current = head
    clone_head = head.next
    while current:
        clone = current.next
        current.next = clone.next
        clone.next = clone.next.next if clone.next else None
        current = current.next

    return clone_head

# Create linked list: 1 -> 2 -> 3 -> None
node3 = Node(3)
node2 = Node(2, node3)
node1 = Node(1, node2)

# Setup random pointers
node1.random = node3
node2.random = node1
node3.random = node2

cloned_head = clone_linked_list(node1)
print_list(cloned_head)
A1(3) -> 2(1) -> 3(2) -> None
B1(None) -> 2(None) -> 3(None) -> None
C1(2) -> 2(3) -> 3(1) -> None
D1(1) -> 2(2) -> 3(3) -> None
Attempts:
2 left
💡 Hint
Focus on how random pointers are copied to the cloned nodes.
🧠 Conceptual
intermediate
1:30remaining
Understanding the purpose of interleaving cloned nodes
Why do we insert cloned nodes between original nodes in the linked list during cloning with random pointers?
ATo reverse the linked list in place
BTo sort the linked list nodes by value
CTo remove duplicate nodes from the list
DTo easily assign random pointers of cloned nodes using original nodes' random pointers
Attempts:
2 left
💡 Hint
Think about how the cloned node can find the clone of the random target without extra space.
🔧 Debug
advanced
1:30remaining
Identify the error in this cloning step
What error will this code cause when cloning the random pointers? current = head while current: current.next.random = current.random.next current = current.next.next
ANo error, code runs correctly
BSyntaxError due to missing colon
CAttributeError when current.random is None
DInfinite loop because current is never updated
Attempts:
2 left
💡 Hint
What if a node's random pointer is None?
❓ Predict Output
advanced
2:00remaining
Output after separating cloned list
Given the interleaved list after cloning nodes, what is the output of printing the original list after separation?
DSA Python
class Node:
    def __init__(self, val, next=None, random=None):
        self.val = val
        self.next = next
        self.random = random

def print_list(head):
    result = []
    current = head
    while current:
        random_val = current.random.val if current.random else None
        result.append(f"{current.val}({random_val})")
        current = current.next
    print(' -> '.join(result) + ' -> None')

# Original list: 1 -> 2 -> None
node2 = Node(2)
node1 = Node(1, node2)
node1.random = node2
node2.random = node2

# Interleaved list: 1 -> 1' -> 2 -> 2' -> None
node1_clone = Node(1)
node2_clone = Node(2)
node1.next = node1_clone
node1_clone.next = node2
node2.next = node2_clone
node2_clone.next = None

# Separate lists
current = node1
while current:
    clone = current.next
    current.next = clone.next
    clone.next = clone.next.next if clone.next else None
    current = current.next

print_list(node1)
A1(2) -> 2(2) -> None
B1(None) -> 2(None) -> None
C1(1) -> 2(1) -> None
D1(2) -> 2(None) -> None
Attempts:
2 left
💡 Hint
Check if original nodes' random pointers remain unchanged after separation.
🚀 Application
expert
1:30remaining
Minimum space complexity for cloning linked list with random pointer
What is the minimum extra space complexity to clone a linked list with random pointers without using a hash map or dictionary?
AO(n) - using a hash map to store original to clone mapping
BO(1) - constant extra space by interleaving cloned nodes
CO(log n) - using recursion stack for cloning
DO(n^2) - by nested loops to find random pointers
Attempts:
2 left
💡 Hint
Think about the interleaving technique that avoids extra data structures.

Practice

(1/5)
1. What is the main challenge when cloning a linked list that has a random pointer in addition to the usual next pointer?
easy
A. Reversing the linked list before cloning
B. Copying the next pointers correctly
C. Ensuring the random pointers in the cloned list point to the correct cloned nodes
D. Sorting the linked list nodes before cloning

Solution

  1. Step 1: Understand the structure of the linked list

    The linked list has two pointers: next and random. The next pointer points to the next node in sequence, while the random pointer can point to any node or null.
  2. Step 2: Identify the cloning challenge

    When cloning, copying next pointers is straightforward, but random pointers must point to the corresponding cloned nodes, not the original nodes.
  3. Final Answer:

    Ensuring the random pointers in the cloned list point to the correct cloned nodes -> Option C
  4. Quick Check:

    Random pointer cloning challenge = Ensuring the random pointers in the cloned list point to the correct cloned nodes [OK]
Hint: Focus on mapping original to cloned nodes for random pointers [OK]
Common Mistakes:
  • Ignoring random pointers and copying only next pointers
  • Setting random pointers to original nodes instead of cloned nodes
  • Assuming random pointers are always null or sequential
2. Which of the following Python code snippets correctly creates a new node with the same value as an existing node curr in a linked list with random pointers?
easy
A. new_node = Node(curr)
B. new_node = Node(curr.val)
C. new_node = Node(curr.next)
D. new_node = Node(curr.random)

Solution

  1. Step 1: Understand the Node constructor

    The Node constructor takes a value to create a new node. To clone a node, we pass the value of the current node.
  2. Step 2: Analyze each option

    new_node = Node(curr.val) passes curr.val, which is the node's value. Options A, C, and D pass node objects or pointers, which is incorrect for creating a new node with the same value.
  3. Final Answer:

    new_node = Node(curr.val) -> Option B
  4. Quick Check:

    Node creation with value = new_node = Node(curr.val) [OK]
Hint: Use node.val to copy value, not the node itself [OK]
Common Mistakes:
  • Passing the node object instead of its value
  • Passing next or random pointers instead of value
  • Confusing node creation syntax
3. Given the following code snippet to clone a linked list with random pointers, what will be the output of the print statement?
class Node:
    def __init__(self, val, next=None, random=None):
        self.val = val
        self.next = next
        self.random = random

def print_list(head):
    curr = head
    result = []
    while curr:
        rand_val = curr.random.val if curr.random else None
        result.append((curr.val, rand_val))
        curr = curr.next
    print(result)

# Original list
node1 = Node(1)
node2 = Node(2)
node3 = Node(3)
node1.next = node2
node2.next = node3
node1.random = node3
node2.random = node1
node3.random = node2

# Cloned list (shallow copy for example)
clone1 = Node(1)
clone2 = Node(2)
clone3 = Node(3)
clone1.next = clone2
clone2.next = clone3
clone1.random = node3
clone2.random = node1
clone3.random = node2

print_list(clone1)
medium
A. [(1, 3), (2, 1), (3, 2)]
B. [(1, None), (2, None), (3, None)]
C. [(1, 1), (2, 2), (3, 3)]
D. [(1, 2), (2, 3), (3, 1)]

Solution

  1. Step 1: Understand the random pointers in the cloned list

    The cloned nodes' random pointers point to the original nodes (node3, node1, node2), not the cloned nodes.
  2. Step 2: Trace the print_list output

    For clone1: val=1, random points to node3 with val=3.
    For clone2: val=2, random points to node1 with val=1.
    For clone3: val=3, random points to node2 with val=2.
    So the printed list is [(1, 3), (2, 1), (3, 2)].
  3. Final Answer:

    [(1, 3), (2, 1), (3, 2)] -> Option A
  4. Quick Check:

    Random pointers show original node values = [(1, 3), (2, 1), (3, 2)] [OK]
Hint: Check if random points to original or cloned nodes [OK]
Common Mistakes:
  • Assuming random points to cloned nodes
  • Printing None for random pointers incorrectly
  • Mixing up node values in output
4. Consider the following code snippet intended to clone a linked list with random pointers. What is the main bug that will cause incorrect cloning?
def clone_list(head):
    if not head:
        return None
    curr = head
    # Step 1: Create new nodes and insert them after original nodes
    while curr:
        new_node = Node(curr.val)
        new_node.next = curr.next
        curr.next = new_node
        curr = new_node.next
    # Step 2: Assign random pointers for new nodes
    curr = head
    while curr:
        if curr.random:
            curr.next.random = curr.random
        curr = curr.next.next
    # Step 3: Separate the cloned list
    curr = head
    clone_head = head.next
    while curr:
        clone = curr.next
        curr.next = clone.next
        if clone.next:
            clone.next = clone.next.next
        curr = curr.next
    return clone_head
medium
A. Random pointers are assigned incorrectly by missing .next on curr.random
B. Random pointers are assigned to original nodes instead of cloned nodes
C. New nodes are not inserted after original nodes
D. The cloned list is not separated from the original list

Solution

  1. Step 1: Analyze random pointer assignment

    In Step 2, the code assigns curr.next.random = curr.random. But curr.random points to an original node, so the cloned node's random pointer points to an original node, not the cloned one.
  2. Step 2: Correct assignment

    The correct assignment should be curr.next.random = curr.random.next to point to the cloned node corresponding to curr.random.
  3. Final Answer:

    Random pointers are assigned incorrectly by missing .next on curr.random -> Option A
  4. Quick Check:

    Random pointer bug = missing .next on curr.random [OK]
Hint: Assign random as curr.next.random = curr.random.next [OK]
Common Mistakes:
  • Assigning random pointer directly to original node
  • Forgetting to separate cloned list
  • Not inserting cloned nodes after originals
5. You want to clone a linked list with random pointers in O(n) time and O(1) extra space. Which approach correctly achieves this? A) Use a hash map to map original nodes to cloned nodes. B) Reverse the original list, clone nodes, then reverse back. C) Create a new list by copying values and random pointers by traversing twice. D) Insert cloned nodes after original nodes, assign random pointers using next pointers, then separate lists.
hard
A. Use a hash map to map original nodes to cloned nodes.
B. Reverse the original list, clone nodes, then reverse back.
C. Create a new list by copying values and random pointers by traversing twice.
D. Insert cloned nodes after original nodes, assign random pointers using next pointers, then separate lists.

Solution

  1. Step 1: Understand space and time constraints

    O(n) time means one or two passes over the list. O(1) extra space means no extra data structures like hash maps.
  2. Step 2: Analyze each approach

    Use a hash map to map original nodes to cloned nodes. uses extra space (hash map), so not O(1) space.
    Insert cloned nodes after original nodes, assign random pointers using next pointers, then separate lists. inserts cloned nodes between original nodes, uses next pointers to assign random pointers correctly, then separates the lists. This uses no extra space and runs in O(n).
    Create a new list by copying values and random pointers by traversing twice. requires extra space or multiple traversals without the in-place trick.
    Reverse the original list, clone nodes, then reverse back. is unrelated and does not solve the problem efficiently.
  3. Final Answer:

    Insert cloned nodes after original nodes, assign random pointers using next pointers, then separate lists. -> Option D
  4. Quick Check:

    In-place cloning with next pointers = Insert cloned nodes after original nodes, assign random pointers using next pointers, then separate lists. [OK]
Hint: Insert clones between originals to avoid extra space [OK]
Common Mistakes:
  • Using hash maps increases space complexity
  • Trying to clone without linking cloned nodes properly
  • Ignoring the need to separate cloned list at the end
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard