Learn Intersection of Two Linked Lists with a step-by-step Linked Lists visualizer, JavaScript source code and a worked example. Practice rewiring and advanced.
INTERACTIVE EXECUTION STUDIO
LEARN BY DOING
Predict. Execute. Understand.
Follow the source code, inspect live state changes, and predict the next operation before revealing it.
Follow the computed execution on the reference input. Advance one step at a time, inspect the changing values and compare your prediction with the final output.
Example input
{
"a": [
0,
2,
3
],
"b": [
1,
4,
2,
3
]
}
Execution steps
Walk both chains, swap at end
Shared node identity
Computed output
2
JavaScript reference implementation
const solve = ({
a,b
},s)=>{
let i=0,j=0,x=a[i],y=b[j],p=a,q=b;
while(x!==y){
s("Walk both chains, swap at end",{
A:a,B:b,Current:[x,y]
});
if(++i>=p.length){
p=p===a?b:a;
i=0
}
if(++j>=q.length){
q=q===a?b:a;
j=0
}
x=p[i];
y=q[j]
}
s("Shared node identity",{
Intersection:[x]
});
return x
};