All problems

Problem 723

Length of a Loop in a Linked List

Easy · 10 pts · Linked List, Two Pointers

Problem

A singly linked list is described by its next pointers, starting at node 0 (see the input format). If the walk from the head enters a loop, print the number of nodes in the loop; otherwise print 0. A node pointing to itself forms a loop of length 1. Once the slow and fast pointers of Floyd's algorithm meet inside the loop, keep one still and move the other around until it comes back, counting the steps.

Input

The first line contains N, the number of nodes (numbered 0 to N-1). The second line contains NEXT[0..N-1], where NEXT[i] is the node that node i points to, or -1 if it points to nothing. The head of the list is node 0.

Output

Print the number of nodes in the loop, or 0 if there is no loop.

Constraints

1 <= N <= 100000; -1 <= NEXT[i] < N

Example input

4
1 2 3 1

Example output

3

Explanation

With NEXT = 1 2 3 1, the loop is 1 → 2 → 3 → 1, which contains the three nodes 1, 2 and 3. So the answer is 3.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Starting Point of a Linked List Cycle Next: Intersection of Two Linked Lists