136. Intersection of Two Linked Lists

Easy · Linked List

Two linked lists may intersect at a node, meaning they share the same tail. You are given two lists encoded as arrays, along with indices indicating where each list's intersection begins. The lists intersect if the suffix of listA starting at index skipA matches the suffix of listB starting at index skipB, and that suffix is non-empty. Return the value of the first node in the shared intersection, or -1 if the lists do not intersect.

Input format: [listA, listB, skipA, skipB] where listA and listB are arrays of node values, and skipA and skipB are the number of nodes to skip before the intersection point in each list respectively.

Examples

Example 1
Input: [[4,1,8,4,5], [5,6,1,8,4,5], 2, 3]
Output: 8
Explanation: Both lists share the suffix [8,4,5]; intersection node value is 8
Example 2
Input: [[2,6,4], [1,5], 3, 2]
Output: -1
Explanation: Both suffixes are empty — no intersection (sentinel: -1)

Constraints