SDE Path

Find Length of a Cycle in Linked List

Medium

Find Length of a Cycle in Linked List

Given a linked list with a cycle, determine the number of nodes in the cycle.

Input format

The first line contains N and POS — the 0-based index the last node links back to (a cycle always exists). The second line contains the N node values.

Output format

Print the number of nodes in the cycle.

Constraints

  • Values fit in a 64-bit signed integer
  • Trailing whitespace and a trailing newline are ignored by the judge

Read from stdin, write to stdout. Sample cases below show the exact format.

Sample cases

Example 1
Input
5 1
1 2 3 4 5
Expected output
4
Example 2
Input
1 0
7
Expected output
1