Linked List Jump GameMedium

Linked List Jump Game

MediumPractice library · +20 XPlinked structurescycle detectiongraph traversal

You are given an array next_indices of length N. Each element next_indices[i] represents a 'jump' from index i to index next_indices[i]. These jumps define a sequence starting from index 0. You repeatedly follow the jumps: from index i, you move to next_indices[i], then to next_indices[next_indices[i]], and so on. This sequence might eventually repeat an index, forming a cycle. Your task is to find the smallest index visited at least twice. If no index is visited twice (i.e., the sequence terminates or visits all indices uniquely before repeating), output -1. Indices are 0-based.

Input

First line contains an integer N. The second line contains N integers, where the i-th integer is next_indices[i].

Output

Print the smallest index that is visited at least twice. If no index is visited twice, print -1.

Constraints

1 <= N <= 200000; 0 <= next_indices[i] < N for all i.

Time limit 1 s (native code; slower languages get more)Memory 256 MB15 hidden tests

Example 1

Input
5
1 2 0 4 3
Output
0

Path: 0 -> 1 -> 2 -> 0. Smallest repeated index is 0.

Example 2

Input
6
1 2 3 4 5 1
Output
1

Path: 0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 1. Smallest repeated index is 1.

Hints