getIntersectionNodeTwoPointer<T> function

LinkedListNode<T>? getIntersectionNodeTwoPointer<T>(
  1. LinkedListNode<T>? headA,
  2. LinkedListNode<T>? headB
)

Finds the intersection point using two-pointer technique

headA - The head of the first linked list headB - The head of the second linked list Returns the intersection node, or null if no intersection exists

Time Complexity: O(n + m) where n and m are the lengths of the lists Space Complexity: O(1)

Implementation

LinkedListNode<T>? getIntersectionNodeTwoPointer<T>(
  LinkedListNode<T>? headA,
  LinkedListNode<T>? headB,
) {
  if (headA == null || headB == null) return null;

  LinkedListNode<T>? pointerA = headA;
  LinkedListNode<T>? pointerB = headB;

  // When pointerA reaches end, move it to headB
  // When pointerB reaches end, move it to headA
  // This way they will meet at intersection point
  while (pointerA != pointerB) {
    pointerA = pointerA == null ? headB : pointerA.next;
    pointerB = pointerB == null ? headA : pointerB.next;
  }

  return pointerA;
}