Find Duplicate Jump TargetMedium

Find Duplicate Jump Target

MediumPractice library · +20 XPlinked structureshash mapsimulation

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]. All next_indices[i] are within the bounds [0, N-1]. Starting from index 0, you repeatedly jump to the index specified by the current index's value. The sequence of visited indices will eventually repeat, forming a cycle. Your task is to find the first index that is visited more than once. If multiple indices are visited for the first time at the same step (i.e., they are part of the cycle entry point), return the smallest index among them.

Input

The first line contains an integer N, the size of the array. The second line contains N space-separated integers representing the next_indices array.

Output

Print a single integer, the smallest index that is visited more than once.

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

The path is 0 -> 1 -> 2 -> 0. Index 0 is the first repeated index.

Example 2

Input
7
1 2 3 4 5 6 0
Output
0

The path is 0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 0. Index 0 is the first repeated index.

Hints