Problem 254933 · medium · Level 02 Linear Data Structures

First Shared Node of Two Lists

linked list · two pointers · identity

Two singly linked lists a and b may share their tail: from some node onwards, both lists consist of exactly the same node objects. Return the value of the first node that belongs to both lists, or None if the lists share no node.

Sharing means the same ListNode object, not merely the same value: two lists that both contain a node with value 8 do not intersect unless it is the same node.

Examples

Input:  a = 1 -> 2 -> 8 -> 9, b = 5 -> 8 -> 9, where the nodes 8 -> 9 are shared
Output: 8

Input:  a = 1 -> 2, b = 1 -> 2, built separately
Output: None

Constraints

  • 0 <= len(a), len(b) <= 10**4
  • Neither list contains a cycle
  • Target: O(len(a) + len(b)) time, O(1) extra space

Goals

  • Distinguish node identity from equal values
  • Align two walks of different lengths without counting
Starting Python…