Linked Lists Fast and slow pointers
292. Intersection of Two Linked Lists
You are given headA and headB, the first nodes of two singly linked lists. The two lists may end in the
same nodes: from some node on, both lists go through exactly the same nodes to the end. Return the first node
that both lists share, or null if they share none.
Shared means the same node, not a node with the same value. Two different nodes can hold equal values. Neither list has a cycle. Do not change the lists: when your function returns, every node must hold its value and point to the node it pointed to before.
The examples write the two lists in three parts, each as its values in order: partA holds the nodes only
list A has, partB the nodes only list B has, and shared the nodes both lists end with. So list A is
partA followed by shared, and list B is partB followed by shared. Your function gets only headA and
headB. In Example 1, partA = [3,9], partB = [7,1,9] and shared = [9,4,6]. These are the two lists,
with the shared nodes filled in:
The output shows the node you return as its index in list A, counted from 0 at the head, and shows null as
-1.
Example 1
Input: partA = [3, 9]
partB = [7, 1, 9]
shared = [9, 4, 6]
2Explanation: The first shared node holds 9 and is the third node of list A, at index 2. The node just before it holds 9 in both lists too, but list A's 9 and list B's 9 are two different nodes.
Example 2
Input: partA = [2, 6, 4], partB = [1, 4], shared = []
-1Explanation: The lists share no node, so the answer is null, shown as -1. Both lists end with a 4, but those are two
different nodes.
Example 3
Input: partA = []
partB = [5, -5]
shared = [-1000000000, 1000000000]
0Explanation: List A has no nodes of its own, so its head is the first shared node. List B reaches that node after its own two nodes.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
0 ≤ number of nodes in each list ≤ 105-109 ≤ Node.val ≤ 109- Neither list has a cycle.
Clarifying questions
What you would ask an interviewer before writing any code.