Search⌘ K
AI Features

Linked List Cycle

Explore how to identify a cycle in a linked list by applying the fast and slow pointer technique. This lesson teaches you to return true if a cycle exists, helping you understand a common pattern tested in coding interviews.

Statement

Given the head of a linked list, determine whether the list contains a cycle. A cycle exists if a node in the list can be revisited by continuously following the next pointers. Return TRUE if a cycle is present; otherwise, return FALSE.

Constraints:

Let n be the number of nodes in a linked list.

  • 00\leq n 500\leq500
  • 105-10^5 \leq Node.value 105\leq 10^5

Examples

Understand the problem

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Linked List Cycle

1.

What is the output if the following linked list is given as an input?

image

A.

TRUE

B.

FALSE


1 / 3

Figure it out!

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3
4

Try it yourself

Implement your solution in the following coding playground.

Java
usercode > Solution.java
// The first input of the test case is an array of values representing a linked list.
// The second input is the index where the tail connects to form a cycle (or −1 if there's no cycle).
// This index is used only to construct the linked list and is not passed to the function.
// Definition for a Linked List node
// class ListNode {
// int val;
// ListNode next;
// // Constructor
// public ListNode(int val) {
// this.val = val;
// this.next = null;
// }
// }
import ds_v1.LinkedList.ListNode;
import java.util.*;
public class Solution{
public static boolean detectCycle(ListNode head) {
// Replace this placeholder return statement with your code
return false;
}
}
Linked List Cycle