#160

Intersection of Two Linked Lists

Easy
Hash TableLinked ListTwo PointersTwo PointersLinked List
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution uses two pointers to traverse both lists. By switching the pointers to the head of the other list after reaching the end, we ensure both pointers traverse the same distance when they meet, thus finding the intersection efficiently.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize two pointers, pointerA at headA and pointerB at headB.
  2. 2Step 2: Traverse both lists; if pointerA reaches the end, redirect it to headB, and similarly for pointerB.
  3. 3Step 3: If the pointers meet, return the intersection node; if they both reach the end (null), return null.
solution.py13 lines
1class ListNode:
2    def __init__(self, val=0, next=None):
3        self.val = val
4        self.next = next
5
6def getIntersectionNode(headA, headB):
7    if not headA or not headB:
8        return None
9    pointerA, pointerB = headA, headB
10    while pointerA != pointerB:
11        pointerA = pointerA.next if pointerA else headB
12        pointerB = pointerB.next if pointerB else headA
13    return pointerA

Complexity note: This complexity is linear because each pointer traverses at most two lists, leading to a total of n steps in the worst case.

  • 1Both lists must be traversed fully to ensure all nodes are checked for intersection.
  • 2Using two pointers allows us to avoid extra space and achieve linear time complexity.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.