Linked List Techniques · 15 min · free lesson

Challenge: Copy with Random Links

Parse values, random (each a node index or null) and optional next (each node's next index or none; when absent, nodes link in array order). Every node is reachable from node 0. Deep-copy the list, following next, with an old-to-new map. Return value:target for each copied node in list order, where target is the random node's position in the copied list, or null. Values may repeat, so identify nodes by index.

Core idea

An old index names a source node, so each link must be rewritten to the matching copied node. Parse values, random (each a node index or null) and optional next (each node's next index or none; when absent, nodes link in array order). Every node is reachable from node 0. Deep-copy the list, following next, with an old-to-new map. Return value:target for each copied node in list order, where target is the random node's position in the copied list, or null. Values may repeat, so identify nodes by index.

Algorithm Atlas · worked example

See the algorithm, step by step

On your device

Map old nodes to new nodes or interleave copies so arbitrary links can be reconstructed.

O(n) time · O(n) old-to-new map and copied nodes29 execution steps
main · before line 61Initialize a local value

This call is starting. Local values appear as they are initialized.

Data & variables

Changed Source index
Example inputvalues=[1] random=[null]

Follow the code. Data appears here when it enters scope.

Call stack · 1 frame
  1. maincall 1

Rust source

Line 61
struct RandomNode {
    value: i32,
    next: Option<usize>,
    random: Option<usize>,
}
fn deep_copy(arena: &[RandomNode], head: Option<usize>) -> Vec<RandomNode> {
    // First pass: give every source node a slot in the new arena, in list order.
    let mut slot = std::collections::HashMap::new();
    let mut copy = Vec::new();
    let mut cursor = head;
    while let Some(old) = cursor {
        slot.insert(old, copy.len());
        copy.push(RandomNode {
            value: arena[old].value,
            next: None,
            random: None,
        });
        cursor = arena[old].next;
    }
    // Second pass: an old index names a source node, so translate every link.
    let mut cursor = head;
    while let Some(old) = cursor {
        let new = slot[&old];
        copy[new].next = arena[old].next.map(|n| slot[&n]);
        copy[new].random = arena[old].random.map(|r| slot[&r]);
        cursor = arena[old].next;
    }
    copy
}
fn copied_pairs(values: &[i32], next: &[Option<usize>], random: &[Option<usize>]) -> String {
    let original: Vec<_> = values
        .iter()
        .enumerate()
        .map(|(i, &value)| RandomNode {
            value,
            next: next[i],
            random: random[i],
        })
        .collect();
    let mut copy = deep_copy(&original, (!original.is_empty()).then_some(0));
    let out = copy
        .iter()
        .map(|n| {
            format!(
                "{}:{}",
                n.value,
                n.random.map_or("null".into(), |i| i.to_string())
            )
        })
        .collect::<Vec<_>>()
        .join(",");
    // The copy owns separate nodes, so changing it leaves the source untouched.
    if !copy.is_empty() {
        copy[0].value += 1;
        assert_ne!(original[0].value, copy[0].value);
    }
    out
}
 
fn main() {
    let result = copied_pairs(&[1], &[None], &[None]);
    println!("{result}");
}

Try your own version

Change the independent fixture `values=[1] random=[null]` in a legal way, then compare the result with your prediction. Explain how the same invariant applies to the separate visible challenge `values=[7,13,11] random=[null,0,1]`.

Open personal copy in Playground ↗

Start with this exact source and input, change a value, then use Run or Debug locally. This replay stays attached to the original example.

Recordings use a native Rust target. Playground runs on wasm32-wasip1; target-sized types such as usize can have different limits.

Recorded from this Rust example and checked against its original output. Playback runs locally in your browser. Values show the state before the highlighted line.
Five-panel Linked List Techniques infographic; panel 4 illustrates Copy Random List.
Copy Random List: follow panel 4 to see the operation, then trace the lesson's own example.

Understand it

An old index names a source node, so each link must be rewritten to the matching copied node. The worked program demonstrates this invariant on an independent fixture, so you can study the implementation before predicting the challenge result.

For teaching input values=[1] random=[null], the worked program returns 1:null. Its functions are complete and use only std. Adapt the same state transitions to the visible challenge input values=[7,13,11] random=[null,0,1]; predict that result before opening the answer reveal. The precise contract is: Parse values, random (each a node index or null) and optional next (each node's next index or none; when absent, nodes link in array order). Every node is reachable from node 0. Deep-copy the list, following next, with an old-to-new map. Return value:target for each copied node in list order, where target is the random node's position in the copied list, or null. Values may repeat, so identify nodes by index.

Return canonical output: lowercase booleans, decimal integers without leading zeros, comma-separated values and semicolon-separated groups, with no extra whitespace or final newline. Whole medians use integer form and half medians use .5. Textual sentinels such as none and # retain their stated meaning. String and character-grid fixtures use ASCII unless the lesson explicitly specifies Unicode scalar values.

Solve the exact task, not just the visible example: Parse values, random (each a node index or null) and optional next (each node's next index or none; when absent, nodes link in array order). Every node is reachable from node 0. Deep-copy the list, following next, with an old-to-new map. Return value:target for each copied node in list order, where target is the random node's position in the copied list, or null. Values may repeat, so identify nodes by index. On input values=[7,13,11] random=[null,0,1], predict the output before opening the answer reveal. The revealed output is a test oracle for this case, while private checks exercise other legal cases. Start by stating the input grammar and output format in your own words. Parse the complete input, including surrounding whitespace, before relying on any convenient positions in the example.

Build the solution around one maintained claim: Map old nodes to new nodes or interleave copies so arbitrary links can be reconstructed. Decide what state represents that claim, how it is initialized, what a single update does, and when the algorithm stops. A list algorithm changes relationships between nodes, not just values. Draw the next pointers before and after each mutation. Trace the visible input by hand and record at least two intermediate states, not only the final answer. If the trace cannot justify your predicted output, there is a gap between the idea and the implementation.

Check both correctness and cost. The intended bound is O(n) time · O(n) old-to-new map and copied nodes; explain which operation dominates it and how many times the input can trigger that operation. Check an empty list, one node, a head or tail change, and cycles when the problem allows them. Add one small case that should succeed, one boundary case, and one case chosen to challenge the invariant. Compare your hand result with the program's result, then use a failing case to fix the earliest incorrect state transition rather than patching the final output.

The pattern

Map old nodes to new nodes or interleave copies so arbitrary links can be reconstructed.

When to use it: deep copy of graphs shaped like a list

Complexity: O(n) time · O(n) old-to-new map and copied nodes

Input: values=[7,13,11] random=[null,0,1]

Read the code

struct RandomNode {
    value: i32,
    next: Option<usize>,
    random: Option<usize>,
}
fn deep_copy(arena: &[RandomNode], head: Option<usize>) -> Vec<RandomNode> {
    // First pass: give every source node a slot in the new arena, in list order.
    let mut slot = std::collections::HashMap::new();
    let mut copy = Vec::new();
    let mut cursor = head;
    while let Some(old) = cursor {
        slot.insert(old, copy.len());
        copy.push(RandomNode {
            value: arena[old].value,
            next: None,
            random: None,
        });
        cursor = arena[old].next;
    }
    // Second pass: an old index names a source node, so translate every link.
    let mut cursor = head;
    while let Some(old) = cursor {
        let new = slot[&old];
        copy[new].next = arena[old].next.map(|n| slot[&n]);
        copy[new].random = arena[old].random.map(|r| slot[&r]);
        cursor = arena[old].next;
    }
    copy
}
fn copied_pairs(values: &[i32], next: &[Option<usize>], random: &[Option<usize>]) -> String {
    let original: Vec<_> = values
        .iter()
        .enumerate()
        .map(|(i, &value)| RandomNode {
            value,
            next: next[i],
            random: random[i],
        })
        .collect();
    let mut copy = deep_copy(&original, (!original.is_empty()).then_some(0));
    let out = copy
        .iter()
        .map(|n| {
            format!(
                "{}:{}",
                n.value,
                n.random.map_or("null".into(), |i| i.to_string())
            )
        })
        .collect::<Vec<_>>()
        .join(",");
    // The copy owns separate nodes, so changing it leaves the source untouched.
    if !copy.is_empty() {
        copy[0].value += 1;
        assert_ne!(original[0].value, copy[0].value);
    }
    out
}

fn main() {
    let result = copied_pairs(&[1], &[None], &[None]);
    println!("{result}");
}

Complete std-only copy-random-list program for its typed teaching fixture. Parsing and output construction are separate from the core algorithm.

Practice starter

pub fn solve(input: &str) -> String {
    // Parse values, random (each a node index or null) and optional next (each node's next index or none; when absent, nodes link in array order). Every node is reachable from node 0. Deep-copy the list, following next, with an old-to-new map. Return value:target for each copied node in list order, where target is the random node's position in the copied list, or null. Values may repeat, so identify nodes by index.
    // Trim surrounding whitespace; implement parsing and the algorithm.
    let _ = input;
    todo!("implement copy-random-list")
}

Try it

Parse values, random (each a node index or null) and optional next (each node's next index or none; when absent, nodes link in array order). Every node is reachable from node 0. Deep-copy the list, following next, with an old-to-new map. Return value:target for each copied node in list order, where target is the random node's position in the copied list, or null. Values may repeat, so identify nodes by index.

What success looks like: The private harness prints PASS copy-random-list. It checks at least five distinct semantic inputs plus surrounding-whitespace variants. Explain complexity separately; this harness does not time the algorithm.

Check your understanding

Boundary check for copy-random-list: with input values=[3,4,5] random=[2,null,0], what result should solve return?

Reveal the answer
  1. 3:2,4:null,5:0
  2. 3:5,4:null,5:3
  3. 3:null,4:null,5:null

For this input the result is 3:2,4:null,5:0. An old index names a source node, so each link must be rewritten to the matching copied node. Compare this independent fixture with the worked trace: With values [7,13,11] and next=[2,none,1], the list order is 7→11→13. The first pass gives the copies slots 0, 1 and 2 in that order. The second pass translates each link: the random target of 11 is source node 1, which holds 13 and lands in slot 2. Changing the copied first value leaves the source unchanged.

Go deeper

Common misconception: “Copying the records as they are gives the right links in any storage order”

An old index names a source node, so each link must be rewritten to the matching copied node. The independent teaching fixture demonstrates this rule; predict the separate visible challenge before revealing its answer.

  1. Pattern-specific invariant: An old index names a source node, so each link must be rewritten to the matching copied node. This is the property the named implementation maintains; explain which comparison, state update or recursive return in the worked program establishes it.
  2. Independent typed fixture: The worked call uses values=[1] random=[null] and computes 1:null. Keep parsing separate, then identify the core state before and after this call.
  3. Different legal case: For values=[3,4,5] random=[2,null,0], the independently calculated result is 3:2,4:null,5:0. The complexity discussion uses O(n) time · O(n) old-to-new map and copied nodes. Verify the state invariant before reasoning about the operation count.

Transfer challenge: Change the independent fixture values=[1] random=[null] in a legal way, then compare the result with your prediction. Explain how the same invariant applies to the separate visible challenge values=[7,13,11] random=[null,0,1].

Connections

  • Copy with Random Links: When to Use It: deep copy of graphs shaped like a list
  • Reverse Nodes in K-Groups: Mental Model: Verify a complete group exists, reverse exactly that range, then reconnect both boundaries.
Reveal the Algorithm Atlas answer

7:null,13:0,11:1

Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: Challenge: Copy with Random Links (courseId "algorithms", lessonId "algorithm.copy-random-list.challenge")
Link: https://crabrix.com/learn/algorithms/algorithm.copy-random-list.challenge
Goal: An old index names a source node, so each link must be rewritten to the matching copied node. Parse values, random (each a node index or null) and optional next (each node's next index or none; when absent, nodes link in array order). Every node is reachable from node 0. Deep-copy the list, following next, with an old-to-new map. Return value:target for each copied node in list order, where target is the random node's position in the copied list, or null. Values may repeat, so identify nodes by index.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=algorithms/algorithm.copy-random-list.challenge) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.