⌘K
Flycodx

Detect Cycle in Linked List

Detect Cycle in Linked List

MediumLinked Lists100% accepted

Given a linked list and a "tail-to" index, determine if the list contains a cycle. The tail-to value indicates which node (0-indexed) the last node's next pointer connects back to. A value of -1 means no cycle — the 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] → the last node (-4) points back to index 1 (value 2), forming a cycle → YES

Input format — only if your code reads from stdin

Input format (stdin): - First line: two integers n (number of nodes) and tail-to index (-1 = no cycle) - Second line: n space-separated integers (node values) Output: YES if the list has a cycle, NO otherwise.

Approach

Floyd's cycle-detection (tortoise and hare): initialize slow = fast = head. Each step: slow moves 1 node, fast moves 2 nodes. If fast or fast.next becomes null, there is no cycle. If slow == fast at any point, a cycle exists.

Input

4 1 3 2 0 -4

Output

YES
  • •0 ≤ n ≤ 10^4, -10^9 ≤ node values ≤ 10^9
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