Find First Duplicate Entry Point
You are given a linked list represented using two arrays: next_val and entry_val. The next_val array stores the index of the next node for each node, and entry_val stores the value of each node. The list starts at index 0. Some nodes might form a cycle. If a cycle exists, find the first node that is part of the cycle. If no cycle exists, output -1. The list will have at most one cycle.
Input
The first line contains an integer N, the number of nodes. The second line contains N integers, the next_val array. The third line contains N integers, the entry_val array.
Output
Print the index of the first node that is part of the cycle, or -1 if no cycle exists.
Constraints
1 <= N <= 200000 0 <= next_val[i] < N for all i 0 <= entry_val[i] <= 10^9 for all i next_val[i] != i for all i
Example 1
5 1 2 3 4 2 10 20 30 40 50
2
The list is 0 -> 1 -> 2 -> 3 -> 4 -> 2. The cycle is 2 -> 3 -> 4 -> 2. The first node in the cycle is index 2.
Example 2
3 1 2 0 5 10 15
0
The list is 0 -> 1 -> 2 -> 0. The cycle is 0 -> 1 -> 2 -> 0. The first node in the cycle is index 0.
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 3 4 2 10 20 30 40 50
3 1 2 0 5 10 15