Linked List Techniques · 15 min · free with an account

Challenge: Copy with Random Links

Lesson preview · about 30%

Return copied values with random target indexes.

Core idea

First make the visible case correct, then test a smallest, duplicate, or adversarial case. Trim whitespace surrounding the complete input before parsing.

Start with the idea

Solve the exact task, not just the visible example: Return copied values with random target indexes. 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.

Use the Rust sketch as a guide, not a substitute for a complete solve function. The supplied Rust sketch is an invariant note rather than a complete program. Turn it into explicit state and transitions before coding. Rust ownership makes linked structures explicit: use the provided node type, take links carefully, and preserve access to the remaining chain.

Keep learning, for free

The rest of this lesson is waiting for you.

Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 742 lessons and algorithm steps are included.

No payment details. Your account opens the complete Academy.

← All lessons in Algorithms