Blind 75 · #23 · Linked List

Linked List Cycle

EasyFast and slow pointersTime O(n)Space O(1)

Linked List Cycle is an easy Linked List problem from the Blind 75. The key pattern is fast and slow pointers, and a good solution runs in O(n) time.

Problem

Given node values and a zero-based tail link position (-1 for none), determine whether the represented list contains a cycle.

Examples

Example 1

Input

{"values":[2,5,9],"tailTo":0}

Output

true

Example 2

Input

{"values":[6,1,8,-3],"tailTo":2}

Output

true

Example 3

Input

{"values":[1],"tailTo":-1}

Output

false

Approach

Move one pointer one step and another two steps at a time. They meet only if the list loops back on itself.

PatternFast and slow pointers
TimeO(n)
SpaceO(1)

Watch out for

Here the cycle is given as a tail link position; -1 means the list ends normally.

More Linked List problems