#K35107. Detect Cycle in a Linked List

    ID: 25458 Type: Default 1000ms 256MiB

Detect Cycle in a Linked List

Detect Cycle in a Linked List

You are given a singly linked list represented in a specific format. The list contains n nodes, each with an integer value. The connectivity of the list is provided by an array of next pointers. For each node, a value of 0 in the next pointer array means the pointer is null (i.e. the end of the list), and a positive integer k means that the next pointer of the current node points to the k-th node (using 1-indexing).

Your task is to determine if the linked list contains a cycle. A cycle exists if there is a sequence of nodes starting and ending at the same node by following the next pointers.

The problem can be formalized as follows: Given an integer \(n\) (the number of nodes), a list of node values \(V = [v_1, v_2, \dots, v_n]\), and a list of next pointers \(P = [p_1, p_2, \dots, p_n]\), where \(p_i = 0\) indicates a null pointer and \(p_i \neq 0\) indicates a pointer to node \(p_i\) (1-indexed), determine whether there exists a cycle in the linked list.

Input Format: The input is read from standard input (stdin). See the input description below.

Output Format: The output should be printed to standard output (stdout) as either True or False.

inputFormat

The input consists of 3 lines:

  • The first line contains an integer \(n\) representing the number of nodes in the linked list.
  • The second line contains \(n\) space-separated integers representing the values of the nodes.
  • The third line contains \(n\) space-separated integers representing the next pointer indices. A value of 0 indicates a null pointer, and any other value (1-indexed) indicates the index of the next node.

\(1 \le n \le 10^5\)

outputFormat

Output a single line with either True if there is a cycle in the linked list, or False if there is no cycle.

## sample
1
1
0
False

</p>