Back to Practice
#0274

Linked List Cycle Detection

EasyDSA18 min10 XP

Problem

A linked list is represented by next_indexes, where next_indexes[i] is the next node index or -1. Starting from head, return True if the path enters a cycle.

Why This Matters

Cycle detection is the reason fast/slow pointers exist; it avoids storing every visited node.

Function Signature

def has_cycle(next_indexes, head):

Examples

Example 1
Inputnext_indexes = [1,2,0], head = 0
OutputTrue

0 -> 1 -> 2 -> 0 forms a cycle.

Constraints

  • Return the exact requested value.
  • Handle edge cases cleanly.
  • Use the intended DSA pattern when brute force would scale poorly.
CodePython
Visible browser tests run here when available.
Testcases2 visible / 3 hidden categories
Cycle exists
Input[1,2,0], head = 0
ExpectedTrue

Fast and slow eventually meet inside the loop.

No cycle
Input[1,2,-1], head = 0
ExpectedFalse

The path reaches the end marker.

Hidden Test Categories
head is -1cycle not starting at headsingle-node self cycle