FastPrepFind the Intersection Node of Two Linked Lists

Find the Intersection Node of Two Linked Lists

Tesla logoTesla● EasyNEW GRADPHONE SCREEN
Learn

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) → int

Examples

Example 1

nodes = [[4,1],[1,2],[8,3],[4,4],[5,-1],[5,6],[6,2]]headA = 0headB = 5return = 2

List 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 = -1

The paths 0 -> 1 and 2 -> 3 share no node identity.

Example 3

nodes = [[7,1],[8,2],[9,-1]]headA = 0headB = 1return = 1

List 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 nodes has exactly two integers: [value, nextIndex].
  • Each nextIndex is -1 or a valid node index.
  • headA and headB are -1 or valid node indices.
  • The chains reachable from both heads are acyclic.
  • -10^9 <= nodes[i][0] <= 10^9.

More Tesla problems

See Tesla hiring insights
public int findIntersectionNodeIndex(int[][] nodes, int headA, int headB) {
  // write your code here
}
nodes[[4,1],[1,2],[8,3],[4,4],[5,-1],[5,6],[6,2]]
headA0
headB5
expected2
Checking account…