LeetCode #160 Easy

Intersection of Two Linked Lists

Intersection of Two Linked Lists is LeetCode 160 (Easy). You get the heads of two singly linked lists. If the lists join, return the first node they share; if they never join, return null.

  • "Share" means the same node in memory, not two nodes that hold the same number.
  • Once two lists join they stay joined, because a node has only one next. So the shape is a Y: two separate starts, one common tail.
  • The follow-up asks for O(m + n) time and O(1) extra memory, and the lists must not be changed.
Constraints
  • 1 <= m, n <= 3 * 10⁴ (the lengths of list A and list B)
  • 1 <= Node.val <= 10⁵
  • The lists contain no cycles, and they must keep their original shape after the function returns.
linked-listtwo-pointers
Open on LeetCode ↗
02

Intuition

If both lists had the same length before the join, you could walk them side by side and the pointers would land on the shared node together. The trouble is that the parts before the join usually differ in length.

Let each pointer walk its own list and then the other one. Pointer a covers A's start, the shared tail, then B's start; pointer b covers B's start, the tail, then A's start. Both routes have the same length, so both pointers arrive at the first shared node on the same move.

When there is no shared tail, the same counting makes both pointers reach null together, and null equals null, so the loop stops.

How to spot this pattern

Two chains that merge into one, and a question about where they meet, points to lining up the distances. Swapping heads lines them up without counting anything, the same way a pointer race finds a loop in a single list.

03

Approach

Try it first

Before reading on, draw a list of 2 nodes and a list of 4 nodes that share their last 2. Count how many moves each pointer needs if it walks its own list and then the other. Do the counts match?

1

Start one pointer on each head

Put a on the head of list A and b on the head of list B. The loop runs while a and b are different nodes, so it compares node identity, never val.

2

Move both pointers one step at a time

On each round, a moves to a.next and b moves to b.next. Both move every round, so the number of moves they have made is always equal.

3

Jump to the other head after falling off the end

When a is null it has finished list A, so its next move puts it on the head of B; b does the same with the head of A. The switch happens after reaching null, not at the last node, so each pointer spends one move on null.

4

Why they meet on the first shared node

Say A has x nodes before the join, B has y, and the tail has t. After x + t + 1 + y moves, a has walked all of A, one null, then B's start, so it is on the join node. b walks y + t + 1 + x moves and reaches the same node at the same moment.

5

Return the node where the loop stopped

The loop stops when a is b. That is either the first shared node, or null on both sides when the lists never join, since then both pointers finish after exactly m + n + 1 moves. Either way, return a.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def getIntersectionNode(
▶3 self, headA: ListNode, headB: ListNode
▶4 ) -> Optional[ListNode]:
▶5 a, b = headA, headB
▶6 while a is not b:
▶7 a = a.next if a else headB
▶8 b = b.next if b else headA
▶9 return a
list Alist Bshared41561845nullaba starts on 4, b starts on 5
moves0
a4
b5
List A has 2 nodes of its own and list B has 3, then both run into the same 3 nodes. The pointers start on different heads, so the loop begins.
list Alist Bshared41561845nullaba moves to 1, b moves to 6
moves1
a1
b6
Both pointers take one step: 1 move each so far. They are on different nodes, so the loop keeps going.
list Alist Bshared41561845nullaba moves to 8, b moves to 1
moves2
a8
b1
Both pointers take one step: 2 moves each so far. They are on different nodes, so the loop keeps going.
list Alist Bshared41561845nullaba moves to 4, b moves to 8
moves3
a4
b8
Both pointers take one step: 3 moves each so far. They are on different nodes, so the loop keeps going.
list Alist Bshared41561845nullaba moves to 5, b moves to 4
moves4
a5
b4
Both pointers take one step: 4 moves each so far. They are on different nodes, so the loop keeps going.
list Alist Bshared41561845nullaba falls off the end, b moves to 5
moves5
anull
b5
a ran past the last node of its list and is now null. Null is not the other pointer, so the loop goes on, and on the next move null sends the pointer to the other list's head.
list Alist Bshared41561845nullaba jumps to B's head, b falls off the end
moves6
a5
bnull
a was on null, so instead of stopping it starts again from B's head. From here each pointer walks the other list, which is what evens out the distances. Still different nodes, so keep going.
list Alist Bshared41561845nullaba moves to 6, b jumps to A's head
moves7
a6
b4
b was on null, so it starts again from A's head. From here each pointer walks the other list, which is what evens out the distances. Still different nodes, so keep going.
list Alist Bshared41561845nullaba moves to 1, b moves to 1
moves8
a1
b1
Both pointers take one step: 8 moves each so far. They hold the same number, 1, but they are two different nodes, so this is not the answer.
list Alist Bshared41561845nullabboth reach 8: the same node, stop
moves9
a8
b8
a walked A's 2 own nodes, the 3 shared ones, one null, then B's 3; b walked the same counts in the other order. That is 9 moves each, which puts both on the first shared node at the same time.
list Alist Bshared41561845nullanswer: the node holding 8
moves9
answer8
Return the node holding 8. It took 9 moves and only two pointers; no lengths were counted and neither list was changed.
05

Count lengths, skip the difference

Count the nodes in each list. Move the pointer of the longer list forward by the difference, so both pointers now have the same number of nodes left. Then step them together; the first time they are the same node is the answer, and if they reach the end together the lists never join.

▶1class Solution:
▶2 def getIntersectionNode(
▶3 self, headA: ListNode, headB: ListNode
▶4 ) -> Optional[ListNode]:
▶5 def length(node: Optional[ListNode]) -> int:
▶6 count = 0
▶7 while node:
▶8 count += 1
▶9 node = node.next
▶10 return count
▶11 
▶12 m, n = length(headA), length(headB)
▶13 a, b = headA, headB
▶14 for _ in range(m - n):
▶15 a = a.next
▶16 for _ in range(n - m):
▶17 b = b.next
▶18 while a is not b:
▶19 a, b = a.next, b.next
▶20 return a
06

Common pitfalls

Comparing values instead of nodes

✗ Wrong
while a.val != b.val:
✓ Right
while a is not b:

Two different nodes can hold the same number. With A = [1, 2] and B = [1] both joining a shared [7], the very first check sees 1 and 1 and returns A's head, but the answer is the node holding 7. Values also crash the loop once a pointer is null.

Switching at the last node instead of at null

✗ Wrong
a = a.next if a.next else headB
b = b.next if b.next else headA
✓ Right
a = a.next if a else headB
b = b.next if b else headA

The pointers then never become null, so when the lists do not join the loop never ends. A = [2, 6, 4] and B = [1, 5] with no shared node runs forever, because a and b keep circling two separate lists.

07

Edge cases

Both heads are the same node

a is b before any move, so the loop body never runs and the head is returned.

One list is the tail of the other

For B = the last 2 nodes of A, B has no nodes before the join (y = 0), and the meeting count x + t + 1 still lands both pointers on B's head.

08

Complexity

Time
O(m + n)
Space
O(1)
Each pointer walks list A once, list B once and one null, so the loop runs at most m + n + 1 times. Only the two pointers are stored, and neither list is changed.
09

Intersection of Two Linked Lists FAQ

Why not store the nodes of list A in a hash set?

It works: put every node of A in a set, then walk B and return the first node already in the set. It costs O(m) extra memory, which is exactly what the follow-up asks you to avoid, so treat it as the first idea to mention in an interview, not the final one.

Can I join the lists into a loop and find where it starts?

Yes. Point A's last node at B's head, and the join node becomes the start of a loop, which the slow and fast pointer method from Linked List Cycle II finds. You must unlink A's tail afterwards, because the problem says the lists must keep their shape.

What if a list could contain a loop?

The head swap relies on both lists ending in null, so a pointer stuck in a loop never switches and the counting breaks. This problem rules loops out; with loops you would first find each list's loop start and compare those.