Linked List Jump Game
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.
Example 1
5 1 2 0 4 3
0
Path: 0 -> 1 -> 2 -> 0. Smallest repeated index is 0.
Example 2
6 1 2 3 4 5 1
1
Path: 0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 1. Smallest repeated index is 1.
Hints
# Read the input from stdin and print the answer.
import sys
def main():
data = sys.stdin.read().split()
# your code here
main()
5 1 2 0 4 3
6 1 2 3 4 5 1