Find Next NodeEasy

Find Next Node

EasyPractice library · +10 XPlinked structuresarray traversalsimulation

You are given a linked list represented using an array. An array next_nodes of size N is given, where next_nodes[i] is the index of the next node after node i. The first node of the list is at index 0. Your task is to find the index of the node that comes immediately after the node at index K. If K is out of bounds or the node K has no next node (indicated by -1), print -1.

Input

The first line contains two integers N and K, separated by a space. The second line contains N integers representing the next_nodes array.

Output

Print a single integer: the index of the node after K, or -1 if it doesn't exist.

Constraints

1 <= N <= 1000 0 <= K < N -1 <= next_nodes[i] < N for all i

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

Example 1

Input
5 2
1 2 3 -1 0
Output
3

N=5, K=2. next_nodes[2] is 3. The node after index 2 is index 3.

Example 2

Input
4 3
1 2 0 -1
Output
-1

N=4, K=3. next_nodes[3] is -1. The node at index 3 has no successor.

Hints