Find End of Linked ListEasy

Find End of Linked List

EasyPractice library · +10 XPlinked structuressimulationarrays

You are given a linked list represented using an array of next pointers. The list is defined by an array next_arr of size N. next_arr[i] stores the index of the next element in the list. The list starts at index 0. If next_arr[i] is -1, it means element i is the last element in the list. Print the index of the last element. If the list is empty (N=0), print -1.

Input

The first line contains an integer N (0 <= N <= 1000). The second line contains N integers, where the i-th integer is next_arr[i] (-1 <= next_arr[i] < N, or next_arr[i] = -1).

Output

Print a single integer, the index of the last element of the linked list. Print -1 if the list is empty.

Constraints

0 <= N <= 1000. -1 <= next_arr[i] < N or next_arr[i] = -1.

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

Example 1

Input
5
1 2 3 4 -1
Output
4

The list is 0 -> 1 -> 2 -> 3 -> 4. The last element is at index 4.

Example 2

Input
3
-1 0 1
Output
0

The list starts at 0, and next_arr[0] is -1, so 0 is the last element.

Hints