Intersection of Two Linked Lists

easy linked list two pointers

Problem

Return the node where two singly linked lists intersect, or null if they don't. Use O(1) extra space and O(m + n) time.

InputA = 1 → 9 → 1 → 2 → 4 ; B = 3 → 2 → 4 ; intersect at node "2"
Outputnode with value 2
If pA hits null, jump to headB; do the same with pB. After at most A + B steps they line up or both reach null.

def getIntersectionNode(headA, headB):
    pA, pB = headA, headB
    while pA is not pB:
        pA = pA.next if pA else headB
        pB = pB.next if pB else headA
    return pA
function getIntersectionNode(headA, headB) {
  let pA = headA, pB = headB;
  while (pA !== pB) {
    pA = pA ? pA.next : headB;
    pB = pB ? pB.next : headA;
  }
  return pA;
}
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode pA = headA, pB = headB;
        while (pA != pB) {
            pA = pA == null ? headB : pA.next;
            pB = pB == null ? headA : pB.next;
        }
        return pA;
    }
}
class Solution {
public:
    ListNode* getIntersectionNode(ListNode* headA, ListNode* headB) {
        ListNode* pA = headA;
        ListNode* pB = headB;
        while (pA != pB) {
            pA = pA ? pA->next : headB;
            pB = pB ? pB->next : headA;
        }
        return pA;
    }
};
Time: O(m + n) Space: O(1)