15% off all plans & roadmaps Use code

See plans

Intersection of Two Linked Lists

Updated

TL;DR: Intersecting lists share every node after the meeting point, so compare node references, not values. Two pointers that switch to the other list after reaching the end meet at that node in O(m + n) time and O(1) space.

Problem

Given the heads of two singly linked lists headA and headB, return the node where the two lists intersect. If the lists do not intersect at all, return null.

For example, two lists can begin to intersect at node c1. The test cases guarantee that no cycles exist anywhere in the linked structure.

The lists must keep their original structure after the function returns.

The judge builds the input from five values. intersectVal is the value of the shared node, or 0 when the lists do not intersect. listA and listB are the two lists. skipA and skipB count how many nodes to walk from each head to reach the shared node. Your function receives only headA and headB.

Example 1

Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3
Output: Intersected at '8'
Explanation: The intersected node's value is 8. The value must not be 0 when the lists intersect. The nodes with value 1 in A and B are different nodes, because they sit at different memory locations. The nodes with value 8 in A and B are the same node.

Example 2

Input: intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
Output: Intersected at '2'
Explanation: The intersected node's value is 2. From the head of A, the list reads [1,9,1,2,4]. From the head of B, it reads [3,2,4]. There are 3 nodes before the intersected node in A, and 1 node before it in B.

Example 3

Input: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
Output: No intersection
Explanation: The lists do not intersect, so intersectVal must be 0. skipA and skipB can be any values in that case. Return null.

Constraints

  • The number of nodes in listA is m.
  • The number of nodes in listB is n.
  • 1 <= m, n <= 3 * 10^4
  • 1 <= Node.val <= 10^5
  • 0 <= skipA <= m
  • 0 <= skipB <= n
  • intersectVal is 0 if listA and listB do not intersect.
  • intersectVal == listA[skipA] == listB[skipB] if listA and listB intersect.

Constraints that matter

  • m and n can reach 3 * 10^4, so the nested scan does up to about 9 * 10^8 comparisons. That rules out brute force as the final answer.
  • Node.val can repeat up to 10^5 distinct values, so matching by value can return a node that is not shared. You must compare references.
  • The follow-up asks for O(1) memory. That rules out a hash set of all nodes of listA, which uses O(m) space.
  • The lists must keep their structure. You cannot sort them, reverse them, or relink them without restoring the links.

View on LeetCode

Hints

Hint 1

Intersection here is about identity.

Hint 2

Compare every node of listA with every node of listB.

Solution

Intuition

Intersection here is about identity. Two lists intersect when they share a node object, and from that node on, both lists read the same nodes. Equal values do not count, because two separate nodes can hold the same number.

Picture two walkers starting at the ends of two roads that merge into one shared road. Each walker walks their own road, then the other, so both cover the same total distance and reach the merge point, which is the intersection node.

The main obstacle is the offset. The two lists can have different lengths, and the shared part can start at a different position in each list. A pointer on each list then reaches the shared node at different steps, so a plain walk misses it.

This page uses two techniques. A hash set remembers every node of one list, which is the natural first idea. Two pointers that switch lists after reaching the end remove the offset without extra memory.

Watch the pattern animation

Worked example

Input: listA = [2,6,4], listB = [1,5], intersectVal = 0 (no shared node), skipA = 3, skipB = 2
Output: null
Explanation: The two lists share no node. Walking A gives 2, 6, 4. Walking B gives 1, 5. No node object appears in both lists, so the answer is null. The skip values do not matter when intersectVal is 0.

Approach 1: Brute force

Compare every node of listA with every node of listB. Two nodes match when they are the same object, and the first match is the answer. This is the first version most people write, and it is correct.

What is slow: each node of listA triggers a full walk of listB. The same nodes of listB are compared again and again, so the work grows with the product of the two lengths.

Steps

  1. Set nodeA to headA.
  2. For each nodeA, set nodeB to headB.
  3. Walk nodeB through listB, checking whether nodeA is nodeB.
  4. If the two references match, return nodeA.
  5. When the walk over listB ends, move nodeA to its next node.
  6. When nodeA runs out, return null.

Dry run

Use listA = [2,6,4] and listB = [1,5]. Compare node 2 with node 1, then with node 5. Neither is the same object, so move to node 6. Compare node 6 with node 1, then with node 5. No match, so move to node 4. Compare node 4 with node 1, then with node 5. No match, and listA ends, so return null after 6 comparisons.

Complexity

TimeO(m * n)
SpaceO(1)

Let m be the length of listA and n the length of listB. The outer loop visits each of the m nodes of listA once. For each one, the inner loop walks up to n nodes of listB, so the work is at most m * n comparisons. The code keeps only two pointers, so the extra space is O(1).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def getIntersectionNode(self, headA: Optional[ListNode], headB: Optional[ListNode]) -> Optional[ListNode]:
        nodeA = headA
        while nodeA:
            nodeB = headB
            while nodeB:
                # Compare references, not values.
                if nodeA is nodeB:
                    return nodeA
                nodeB = nodeB.next
            nodeA = nodeA.next
        return None

Approach 2: One-pass hash set

What is slow: the brute force walks listB again for every node of listA. The insight that fixes it is memory of what you have seen. A hash set answers whether a node was seen in constant average time.

Store every node reference of listA in the set. Then walk listB once and ask the set about each node. The first node of listB found in the set is the shared node.

The set must hold node references, not values. The ListNode class in these templates does not override equality or hashing, so the set compares references.

Steps

  1. Create an empty set named seen.
  2. Walk listA from headA, adding each node reference to seen.
  3. Walk listB from headB.
  4. For each node in listB, check whether it is in seen.
  5. Return the first node found in seen. If none is found, return null.

Dry run

Use listA = [2,6,4] and listB = [1,5]. Adding the nodes of A puts the references to 2, 6 and 4 into seen. Walk listB. Node 1 is not in seen. Node 5 is not in seen. listB ends, so return null. The set held 3 nodes, and the walk made 2 lookups.

Complexity

TimeO(m + n)
SpaceO(m)

Adding the m nodes of listA costs m set insertions. Looking up the n nodes of listB costs n lookups. Each insertion and lookup takes O(1) on average, so the total is O(m + n). The set stores up to m node references, so the space is O(m).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def getIntersectionNode(self, headA: Optional[ListNode], headB: Optional[ListNode]) -> Optional[ListNode]:
        # Python hashes objects by identity unless __hash__ is overridden.
        seen = set()
        node = headA
        while node:
            seen.add(node)
            node = node.next
        node = headB
        while node:
            if node in seen:
                return node
            node = node.next
        return None

The Intersection Detection infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Intersection Detection

Part of Linked List Manipulation Patterns

Approach 3: Two pointers that switch listsOptimalIntersection Detection

What is slow: the hash set uses O(m) memory, and the follow-up asks for O(1). The insight is that the length offset cancels out when each pointer walks both lists. Pointer A walks listA, then continues from headB. Pointer B walks listB, then continues from headA.

Why it is correct. Each pointer walks its own list and then the other list, so each travels exactly m + n nodes. Both pointers spend a + b steps on unshared nodes before reaching the shared tail, so they arrive at the same node together. If the lists never intersect, both pointers reach null at the same step, so the loop still ends and returns null.

Steps

  1. Set ptrA to headA and ptrB to headB.
  2. While ptrA is not ptrB, move ptrA one node forward.
  3. If ptrA became null, set it to headB.
  4. Move ptrB one node forward in the same way, and set it to headA when it becomes null.
  5. When the loop stops, return ptrA. It is the shared node or null.

Dry run

Use listA = [2,6,4] and listB = [1,5]. The table tracks both pointers after each step.

StepptrAptrBEqual?
021no
165no
24null (past 5)no
3null (past 4)2 (switched to headA)no
41 (switched to headB)6no
554no
6nullnullyes, return null

Both pointers reach null on the same step, so the answer is null.

Complexity

TimeO(m + n)
SpaceO(1)

Let m and n be the lengths of the two lists. Both pointers cover the same total distance before they meet, so the loop runs at most m + n times. Call the shared tail length C. Pointer A covers (m - C) + C + (n - C) steps to reach the shared node, and pointer B covers the same total. The code stores only two pointers, so the space is O(1).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def getIntersectionNode(self, headA: Optional[ListNode], headB: Optional[ListNode]) -> Optional[ListNode]:
        ptrA, ptrB = headA, headB
        # A pointer that runs off its list continues on the other list.
        while ptrA is not ptrB:
            ptrA = ptrA.next if ptrA else headB
            ptrB = ptrB.next if ptrB else headA
        return ptrA

Common mistakes

  • Comparing node.val values inside the loop, as in if ptrA.val == ptrB.val. Two different nodes can both hold 1. Compare the node references instead.
  • Writing ptrA = ptrA.next with no switch. When ptrA is null, reading .next crashes. Check for null first and redirect to headB.
  • Switching both pointers to the same head, such as both to headA. Each pointer must switch to the other list, so ptrA goes to headB and ptrB goes to headA.
  • Stopping the loop when either pointer hits null, as in while ptrA and ptrB. The switch is what lets the pointers meet, so the loop must run until the pointers are the same object.
  • Sorting either list to line up matches. Sorting reorders the nodes, which breaks the structure the problem says to keep. It also compares values, not references.
  • Storing values in the hash set with seen.add(node.val). A value match does not identify the shared node. Store the node reference, as in the hash set approach.

Edge cases

  • Either head is null. No node can be shared, so the answer is null. All three approaches return null here.
  • The two heads are the same node. The lists share everything from the start, so the answer is headA. The two-pointer loop exits on its first check.
  • The lists share only their last node. The shared tail has length 1, so the pointers meet on that node after m + n - 1 steps.
  • Equal values in different nodes, such as [1] and [1] with no shared node. The answer is null, because the nodes are different objects.
  • listB is a suffix of listA, such as listB starting at the second node of listA. The answer is that second node of listA, which is the start of listB.
  • Maximum size: m = n = 3 * 10^4 with a shared tail of 3 * 10^4 nodes. The two-pointer loop finishes in at most 6 * 10^4 steps.

Follow-ups interviewers ask

Follow-ups are part of Pro

The questions interviewers ask after you solve Intersection of Two Linked Lists, with how to answer them.

Unlock the follow-ups

Intersection of Two Linked Lists FAQ

What is the time complexity of Intersection of Two Linked Lists?

The brute force takes O(m * n) time. The hash set and the two-pointer approaches both take O(m + n) time, where m and n are the list lengths. The two-pointer approach is the one that also uses O(1) space.

Why use two pointers for Intersection of Two Linked Lists?

Two pointers that switch lists cancel out the difference in lengths. Both pointers cover the same total distance before reaching the shared node. This removes the need to remember nodes, so the extra space is O(1).

Can Intersection of Two Linked Lists be solved in O(1) extra space?

Yes. The two-pointer switch method stores only two references and never builds a data structure. No extra memory grows with the input size.

Why compare node references instead of values?

The problem defines an intersection as a shared node object. Two separate nodes can hold the same value, so value equality can return a node that is not shared.

Can I sort the lists to find the intersection?

No. Sorting reorders the nodes and breaks the original structure, which the problem forbids. Sorting by value also loses the identity of each node.

Asked at

See which companies ask this — Pro

Practise it