Linked List Techniques · 15 min · free lesson

Copy with Random Links: When to Use It

Recognise the problem shape before choosing Copy with Random Links.

Core idea

An old index names a source node, so each link must be rewritten to the matching copied node. State the input preconditions before applying this invariant.

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 nodes55 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=[7,13,11] random=[null,0,1]

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(
        &[7, 13, 11],
        &[Some(1), Some(2), None],
        &[None, Some(0), Some(1)],
    );
    println!("{result}");
}

Try your own version

Compare the visible input `values=[7,13,11] random=[null,0,1]` with `values=[9] random=[0]`. Predict why their results are `7:null,13:0,11:1` and `9:0`. Then change one legal value and explain whether the same invariant, an old index names a source node, so each link must be rewritten to the matching copied node, still applies.

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 this lesson's example.

Understand it

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.

The worked program is a complete executable for this pattern. Its core function uses typed input so the state transitions remain visible. The challenge input 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. The visible fixture is values=[7,13,11] random=[null,0,1] and its example result is 7:null,13:0,11:1. The implementation and additional semantic fixtures were checked against an independent reference calculation. Those bounded tests establish these examples; they are not a proof for all inputs or a measurement on an iPhone.

Return a canonical String from solve: lowercase true/false for booleans; decimal integers without extra signs, leading zeros or whitespace; comma-separated sequence values and semicolon-separated groups. Whole-number medians have no decimal suffix; half medians use .5. Do not append a newline to the returned value. Preserve the explicitly named textual sentinels such as none or #. Input fixtures are bounded so the demonstrated arithmetic fits its named Rust types; satisfy the stated input preconditions before applying the algorithm.

String and character-grid fixtures use ASCII unless the lesson explicitly specifies Unicode scalar values.

A problem is a good match for Copy with Random Links when it asks for deep copy of graphs shaped like a list. Here the concrete task 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. The visible input values=[7,13,11] random=[null,0,1] is an example, not a definition of the whole problem. Ask what operations the solution must support and what the input guarantees. Look for tasks where node identity or one-way traversal matters. An indexed vector solution can hide the pointer constraint rather than solve it. The right choice follows from those guarantees, not from a familiar noun in the prompt.

The decisive invariant is: Map old nodes to new nodes or interleave copies so arbitrary links can be reconstructed. Try to say why it applies to the task without quoting the implementation. Which fact becomes known after one update, and which possible answers remain? A list algorithm changes relationships between nodes, not just values. Draw the next pointers before and after each mutation. If that claim cannot be maintained on a legal input, the pattern is wrong or one of its preconditions is missing. A counterexample is more useful than a vague warning: change one property of the sample, trace the first two steps, and identify the exact claim that fails.

Compare costs before committing. The advertised bound is O(n) time · O(n) old-to-new map and copied nodes; identify the operation responsible for it and the extra memory it needs. Then compare a straightforward alternative: a direct scan, full sort, or repeated recomputation may be easier but can pay for the same work many times. Do not choose the more elaborate method just because it has a famous name. For the sample, predict 7:null,13:0,11:1 and explain which part of the state lets the method reach that result.

When the prompt is ambiguous, ask about input size, ordering, duplicates, and required output format. Check an empty list, one node, a head or tail change, and cycles when the problem allows them. Rust ownership makes linked structures explicit: use the provided node type, take links carefully, and preserve access to the remaining chain. The Rust sketch can show a useful primitive without proving that the whole task is solved; connect each primitive to the requested output. You should be able to name a fitting case, a near miss, and the assumption separating them before writing the first line.

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(
        &[7, 13, 11],
        &[Some(1), Some(2), None],
        &[None, Some(0), Some(1)],
    );
    println!("{result}");
}

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

Try it

Compare the visible and independent fixtures. Explain the input assumption that makes this algorithm applicable, then identify a change that would invalidate it.

What success looks like: You can justify the choice from constraints rather than from a remembered problem title.

Check your understanding

Trace Copy with Random Links on input values=[1,2] random=[1,0]. Which result follows from the documented contract?

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

For this input the result is 1:1,2: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. 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.

  1. Concrete transition: 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.
  2. Independent second fixture: Input values=[1,2] random=[1,0] produces 1:1,2:0. Execute the named function in the worked program with these typed arguments, then compare its actual result with this independently computed expectation.
  3. Boundary and contract: Input values=[3,4,5] random=[2,null,0] produces 3:2,4:null,5:0. An old index names a source node, so each link must be rewritten to the matching copied node. The stated work bound is O(n) time · O(n) old-to-new map and copied nodes. Count actual state changes; a successful output test alone does not prove that bound.

Transfer challenge: Compare the visible input values=[7,13,11] random=[null,0,1] with values=[9] random=[0]. Predict why their results are 7:null,13:0,11:1 and 9:0. Then change one legal value and explain whether the same invariant, an old index names a source node, so each link must be rewritten to the matching copied node, still applies.

Connections

  • Copy with Random Links: Mental Model: Map old nodes to new nodes or interleave copies so arbitrary links can be reconstructed.
  • 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.
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: Copy with Random Links: When to Use It (courseId "algorithms", lessonId "algorithm.copy-random-list.recognize")
Link: https://crabrix.com/learn/algorithms/algorithm.copy-random-list.recognize
Goal: An old index names a source node, so each link must be rewritten to the matching copied node. State the input preconditions before applying this invariant.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=algorithms/algorithm.copy-random-list.recognize) 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.