Notice Period

Linked List Cycle

easy

A job scheduler chains tasks with "run next" pointers. A misconfigured deploy may have created a loop — a task whose chain eventually points back to an earlier task, so the worker never terminates. You must detect this without extra memory: the chain is millions of nodes and the on-call budget for your check is O(1) space.

Given the head of a linked list, return True if the list contains a cycle, else False.

Tests describe the list as values plus pos: the tail's next pointer is wired to the node at index pos (-1 means no cycle). The harness builds that structure; your job is _has_cycle(head) on real nodes.

Example 1
in values = [3, 2, 0, -4], pos = 1
out True
The tail (-4) points back to index 1 (value 2).
Example 2
in values = [1, 2], pos = 0
out True
Example 3
in values = [1], pos = -1
out False
Constraints
  • · 0 <= number of nodes <= 10^4
  • · -10^5 <= node value <= 10^5
  • · pos is -1 or a valid index
  • · O(1) extra space
similar problem on LeetCode ↗
solution.pyloading python…
test results
Hit ▶ Run to test your code against the visible cases.