All problems

Problem 724

Intersection of Two Linked Lists

Easy · 10 pts · Linked List, Two Pointers

Problem

N nodes are linked by next pointers (NEXT[i] is the node after node i, or -1). List A starts at node HA and list B starts at node HB; neither list has a cycle. The two lists may merge at some node and share all nodes from there on. Print the first shared node, or -1 if they never meet. Two pointers that each walk their own list and then switch to the head of the other list travel the same distance and meet at the intersection (or both reach the end together).

Input

The first line contains N, HA and HB. The second line contains NEXT[0..N-1]. The lists starting at HA and HB contain no cycles.

Output

Print the first node shared by both lists, or -1.

Constraints

1 <= N <= 100000; 0 <= HA, HB < N; -1 <= NEXT[i] < N

Example input

6 0 4
1 2 3 -1 5 2

Example output

2

Explanation

With NEXT = 1 2 3 -1 5 2, list A is 0 → 1 → 2 → 3 and list B is 4 → 5 → 2 → 3. They first share node 2, so the answer is 2.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Length of a Loop in a Linked List Next: Flatten a Multilevel Linked List