> Uploading knowledge... _
[░░░░░░░░░░░░░░░░░░░░░░░░] 0%
blog logo
> CHICIO CODING_Pixels. Code. Unplugged.

Intersection of Two Linked Lists

Leetcode Problem 160: Intersection of Two Linked Lists

Problem Summary

Given the heads of two singly linked lists, return the node at which the two lists intersect, or null if they do not intersect. The intersection is by reference (same node object), not by value.

Constraints:

  • Each list has between 1 and 30,000 nodes.
  • Node values are integers in the range [1, 50,000].
  • The lists may or may not intersect.

Techniques

  • Hash Table
  • Linked List
  • Two Pointers

Solution

import { ListNode } from "../list-node"

function getIntersectionNode(headA: ListNode | null, headB: ListNode | null): ListNode | null {
    if (!headA || !headB) {
        return null
    }

    let currentA: ListNode | null = headA
    let currentB: ListNode | null = headB

    while (currentA !== currentB) {
        currentA = currentA === null ? headA : currentA.next
        currentB = currentB === null ? headB : currentB.next
    }

    return currentA
};