All problems

Problem 722

Starting Point of a Linked List Cycle

Medium · 20 pts · Linked List, Two Pointers

Problem

A singly linked list is described by its next pointers, starting at node 0 (see the input format). If following the pointers from the head enters a cycle, print the node where the cycle begins: the first node on the cycle that the walk reaches. Otherwise print -1. After the slow and fast pointers of Floyd's algorithm meet, move one pointer back to the head and advance both one step at a time; they meet again exactly at the start of the cycle.

Input

The first line contains N, the number of nodes (numbered 0 to N-1). The second line contains NEXT[0..N-1], where NEXT[i] is the node that node i points to, or -1 if it points to nothing. The head of the list is node 0.

Output

Print the node where the cycle starts, or -1 if there is no cycle.

Constraints

1 <= N <= 100000; -1 <= NEXT[i] < N

Example input

4
1 2 3 1

Example output

1

Explanation

With NEXT = 1 2 3 1, the walk is 0 → 1 → 2 → 3 → 1 → ..., and node 1 is the first node that repeats. So the cycle starts at node 1.

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

Previous: Linked List Cycle Next: Length of a Loop in a Linked List