Wire Cloned Records
Checking your account…
Sign in to save your code and progress across devices. The lesson and problem statement remain public.
Loading the interactive Practice workspace.If it does not appear, the problem and learning material remain readable, but browser execution is unavailable.Reload Practice workspace
Problem
Implement wire_cloned_records(records). Each input record is [label, random_index], where random_index is an index into records or -1. Return newly allocated two-item lists containing the same labels and random indices. Do not reuse any input inner list.
Starter code
def wire_cloned_records(records):
passTest cases
cross-links
{
"args": [
[
[
"a",
2
],
[
"b",
-1
],
[
"c",
0
]
]
]
}Expected: [["a",2],["b",-1],["c",0]]
self-link
{
"args": [
[
[
"only",
0
]
]
]
}Expected: [["only",0]]
Wizard outline
- Step 1: Allocate the empty clone map
Return an empty ordered clone list when no source records exist. The empty case fixes output shape before clone identities and links are introduced.
- Step 2: Clone values with null links
Allocate a new two-item record for every source while initializing its random link to -1. Separating allocation from wiring ensures every target identity exists before an edge is processed.
- Step 3: Wire arbitrary random indexes
Copy every source random_index into the already allocated clone with the same stable index. Once allocation is complete, cross-links and self-links are both ordinary index assignments.
Footguns and prerequisites
- Returning records.copy() creates only a new outer list and still aliases every inner record.
- Treating -1 as a Python index accidentally links null relationships to the final record.
- hashing and sets
Reviewed references
Prepared Interview Problems
- Copy a Random-Pointer List(opens in a new tab)
Wire Cloned Records isolates clone_by_index maps every original position to exactly one new record before any copied relationship is resolved. That focused state discipline is required when implementing copy random pointer records as a complete Interview Problem.
Recommended approach and implementation
Objects with cross-links are safest to clone in two phases: allocate every clone, then wire relationships through a stable identity map. clone_by_index maps every original position to exactly one new record before any copied relationship is resolved.
Why it works: The first pass creates one independent two-item clone per original index and copies each label. The second pass copies the corresponding random index into that clone, so every returned [label, random_index] pair matches the input without reusing an input inner list.
def wire_cloned_records(records):
clones = {index: [record[0], -1] for index, record in enumerate(records)}
for index, (_, random_index) in enumerate(records):
clones[index][1] = random_index
return [clones[index] for index in range(len(records))]