Find the Intersection Node of Two Linked Lists
Problem statement
Two singly linked lists are represented by one shared node table. Row nodes[i] describes node identity i as [value, nextIndex], where nextIndex is another node index or -1.
The two lists start at headA and headB. Because both heads use the same node table, reaching the same node index means the lists intersect by identity.
Return the index of the first shared node, or -1 if the lists do not intersect. Do not modify nodes.
Function
findIntersectionNodeIndex(nodes: int[][], headA: int, headB: int) → intExamples
Example 1
nodes = [[4,1],[1,2],[8,3],[4,4],[5,-1],[5,6],[6,2]]headA = 0headB = 5return = 2List A is 0 -> 1 -> 2 -> 3 -> 4, and list B is 5 -> 6 -> 2 -> 3 -> 4. Their first shared node is index 2.
Example 2
nodes = [[1,1],[2,-1],[3,3],[4,-1]]headA = 0headB = 2return = -1The paths 0 -> 1 and 2 -> 3 share no node identity.
Example 3
nodes = [[7,1],[8,2],[9,-1]]headA = 0headB = 1return = 1List B begins inside list A, so its head at index 1 is the first shared node.
Constraints
0 <= nodes.length <= 10^5.- Every row of
nodeshas exactly two integers:[value, nextIndex]. - Each
nextIndexis-1or a valid node index. headAandheadBare-1or valid node indices.- The chains reachable from both heads are acyclic.
-10^9 <= nodes[i][0] <= 10^9.