Linked List Cycle
Linked List Cycle
Given a linked list, determine if it has a cycle. A cycle exists if some node's next pointer points to a previously visited node, causing the traversal to loop forever. The input provides the tail-to index: the last node connects back to this 0-based index (-1 means no cycle, last node points to null). Your solve(...) function receives these inputs directly as ready-made arguments — no input reading or parsing needed. Just compute and return the answer. Example: n=4, tail-to=1, values=[3 2 0 -4] → node -4 connects to node at index 1 (value 2) → YES
Input format — only if your code reads from stdin
Input format (stdin): - First line: two integers n (nodes) and tail-to (-1 = no cycle) - Second line: n space-separated integers (node values) Output: YES if cycle exists, NO otherwise.
Approach
Floyd's cycle-detection algorithm: use two pointers — slow (1 step at a time) and fast (2 steps at a time). If fast ever catches up to slow, a cycle exists. If fast reaches null, no cycle.
Input
Output
- •
0 ≤ n ≤ 10^4, -10^5 ≤ node values ≤ 10^5
More Linked Lists problems
Browse all coding problems →Press Run to test your custom input, or Submit to judge against all test cases.
Sign in to continue
Create a free account to run code, submit solutions and track progress.
- Free forever — no credit card
- 10+ languages with live execution
- Points, streaks & leaderboards