Find Path Length
EasyPractice library · +10 XPlinked structuressimulationtraversal
You are given a simulation of a linked list using arrays. An array next_indices of size N is provided, where next_indices[i] contains the index of the next element in the list, starting from index 0. If next_indices[i] is -1, it signifies the end of the list. Your task is to determine the length of this linked list (the number of nodes visited from the start until the end is reached).
Input
The first line contains an integer N, the size of the next_indices array. The second line contains N space-separated integers, representing the next_indices array.
Output
Print a single integer, the length of the linked list.
Constraints
1 <= N <= 1000 0 <= next_indices[i] < N or next_indices[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
5
A simple list of length 5.
Example 2
Input
3 1 2 -1
Output
3
A list of length 3.
Hints
# Read the input from stdin and print the answer.
import sys
def main():
data = sys.stdin.read().split()
# your code here
main()
Example 1 input
5 1 2 3 4 -1
Example 2 input
3 1 2 -1