#K68412. Cycle Detection in a Linked List

    ID: 32859 Type: Default 1000ms 256MiB

Cycle Detection in a Linked List

Cycle Detection in a Linked List

In this problem, you are given a representation of a linked list using two inputs: an integer (n) that denotes the number of nodes and an array of (n) integers that represent the next pointer of each node. The next pointer for the (i^{th}) node is provided in a 1-indexed fashion: a value of -1 indicates the end of the list. Your task is to determine whether the linked list contains a cycle.

If a cycle exists, output True; otherwise, output False.

Note:
- When (n=0), the list is empty and should be considered as having no cycle.
- Efficient cycle detection algorithms such as Floyd's Cycle Detection (tortoise and hare) are recommended.

inputFormat

The input is given via standard input (stdin).

The first line contains a single integer (n) ((0 \le n \le 10^5)), representing the number of nodes in the linked list. If (n > 0), the second line contains (n) space-separated integers. Each integer represents the next pointer of the corresponding node (1-indexed), where a value of -1 indicates the end of the list.

outputFormat

Print a single line to standard output (stdout) containing either True if a cycle exists in the linked list or False if it does not.## sample

0
False