Problem 721
Linked List Cycle
Easy · 10 pts · Linked List, Two Pointers
Problem
A singly linked list is described by its next pointers: node i points to node NEXT[i], or to nothing when NEXT[i] = -1, and the list starts at node 0. Some nodes may not be reachable from the head at all. Decide whether following the pointers from the head ever runs into a cycle. Floyd's algorithm uses two pointers, one moving one step and one moving two steps at a time; they meet exactly when there is a cycle, using O(1) extra memory.
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 YES if the list starting at node 0 has a cycle, otherwise NO.
Constraints
1 <= N <= 100000; -1 <= NEXT[i] < N
Example input
4 1 2 3 1
Example output
YES
Explanation
With NEXT = 1 2 3 1, the walk goes 0 → 1 → 2 → 3 → 1 → 2 → ..., returning to node 1 forever. So the list has a cycle and the answer is YES.