⌘K
Flycodx

Linked List Cycle

Linked List Cycle

EasyLinked Lists100% accepted

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

4 1 3 2 0 -4

Output

YES
  • •0 ≤ n ≤ 10^4, -10^5 ≤ node values ≤ 10^5
solution.py
Loading editor...
Test 1
Test 2
Test 3

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
Auto Save OnLn 1, Col 1Spaces: 4UTF-8LFPython 3