Workspace Intersection Of Two Linked Lists
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Intersection of Two Linked Lists visualizer

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.

1 / 7Execution step
Reference example · JavaScript
Inspect reference input
{
  "a": [
    0,
    2,
    3
  ],
  "b": [
    1,
    4,
    2,
    3
  ]
}

Algorithm source

JavaScript reference implementation · highlighted trace statement
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
};

Execution canvas

Active Changed
STEP 1

Walk both chains, swap at end

Inspect the highlighted code and the state below. Click individual cells or nodes to see their values.

A3 items
B4 items
Current2 items
Keyboard: Space to play · Left / Right to stepExplore next problem

Worked example and algorithm walkthrough

Topic: Linked Lists · Rewiring and advanced

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

  1. Walk both chains, swap at end
  2. 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
};

Continue learning

Practice related DSA questions in the same topic.