Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Detect a cycle using Floyd’s algorithm

Detect whether a singly linked list has a cycle using Floyd's Tortoise and Hare algorithm.

Python practice15 minLinked ListsIntermediateLast updated March 27, 2026

Problem statement

Given a list of values and an integer pos, build a singly linked list from the values. If pos >= 0, connect the tail's next pointer to the node at index pos (0-based) to create a cycle. Implement Floyd's cycle-detection algorithm (fast and slow pointers) to determine whether the linked list contains a cycle. Return True if a cycle exists, otherwise False.

Task

Build a linked list from a list of values and a cycle position, apply Floyd's cycle-finding algorithm and return True if a cycle exists.

Examples

Cycle exists

Input

[3,2,0,-4], 1

Output

True

Tail connects to node index 1, creating a cycle.

Input format

Two arguments: a Python list of integers and an integer pos. pos is the index (0-based) where the tail connects. pos = -1 means no cycle.

Output format

A boolean: True if a cycle exists, otherwise False.

Constraints

0 <= len(values) <= 10^5. -1 <= pos < len(values) (if pos != -1). Use O(1) extra space and O(L) time.

Samples

Sample 1

Input

[3,2,0,-4], 1

Output

True

There is a cycle because tail connects to index 1.