Menu
CoddyTech

Intersection of Two Linked Lists

Two singly linked lists live in one pool of nodes. Node i links to node next[i], and -1 ends a list. List A starts at node headA and list B at node headB. The nodes are stored in no particular order, so follow the links.

The two lists may run into each other: from some node on, they continue through the same nodes to the end. Return the index of the first node that is on both lists, or -1 if they share no node.

Function

getIntersectionNode(next: integer-array, headA: integer, headB: integer) → integer
nextinteger-array
the index of the node each node links to, or -1 for the last node of a list
headAinteger
the first node of list A
headBinteger
the first node of list B
Returnsinteger
the first node the two lists share, or -1

Constraints

  • 2 ≤ n ≤ 104, where n is the length of next.
  • Each next[i] is -1 or a node index from 0 to n-1.
  • 0 ≤ headA, headB ≤ n-1 and headA ≠ headB.
  • Both lists end at -1 without visiting a node twice. There is no cycle.
  • Every node is on list A, on list B, or on both.

Examples

Input
next = [-1, 4, 1, 5, 0, 1]headA = 3headB = 2
Output
1
Explanation
A visits 3, 5, 1, 4, 0 and B visits 2, 1, 4, 0. From node 1 on they share every node, and no earlier node of A is on B, so the answer is 1.
challenge icon

Follow-up

Can you find the node in O(m + k) time with O(1) extra memory?

Reset code
def getIntersectionNode(next, headA, headB):
    # Write code here

Test #1

Test #2

Test #3

Arguments

next = [-1, 4, 1, 5, 0, 1]
headA = 3
headB = 2

Expected Output

1