Back

Linked List Cycle

easy

Given head, the head of a linked list, determine if the linked list has a cycle in it.

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer.

Return true if there is a cycle in the linked list. Otherwise, return false.

Test Cases

Copy an input into the main harness and Run to verify
Input
head = [3,2,0,-4], pos = 1
Expected Output
true

Explanation: There is a cycle where the tail connects to the node at index 1.

Input
head = [1,2], pos = 0
Expected Output
true
Input
head = [1], pos = -1
Expected Output
false

Constraints

  • The number of the nodes in the list is in the range [0, 10^4].
  • -10^5 <= Node.val <= 10^5
  • pos is -1 or a valid index in the linked list.

Hints

Hint 1 — click to reveal

Floyd's cycle finding: two pointers moving at different speeds.

Hint 2 — click to reveal

If a cycle exists, the fast pointer will eventually lap the slow one.

Java Compiler

Powered by OneCompiler. Starter code loads automatically — edit and hit Run.