← Back to Codes

2026-06-09 16:36:42

Linked List Cycle in Python and Java | LeetCode #141

Learn how to solve Linked List Cycle in Python and Java with beginner-friendly explanation, step-by-step dry run, custom examples, and time complexity.

Linked List Cycle in Python and Java

In this tutorial, we will learn LeetCode #141: Linked List Cycle in very simple language. We will understand the idea step by step, see custom examples, and write complete code in Python and Java.

What Is the Linked List Cycle Problem?

This problem asks us to solve a common coding interview task using the given input. The goal is to return the correct result without using a slow brute force method.

For this problem, we will use fast and slow pointers because it gives a clean and optimized solution.

Example input:
head = [5, 8, 3, 1], pos = 1

Expected result:
Output: true

Explanation:
The tail connects back to node 8.

Beginner-Friendly Idea

The main idea is to avoid trying every possible answer blindly. Instead, we keep useful information while reading the input and use that information to make the next decision.

At each step, ask: “What do I already know, and how does the current value change my answer?”

Using our example:
head = [5, 8, 3, 1], pos = 1

Approach:
fast and slow pointers

We update variables step by step until we reach:
Output: true

Why Do We Use This Approach?

A direct brute force solution is usually easier to think about, but it can become slow when the input is large. The optimized approach keeps only the important state and avoids repeated work.

That is why fast and slow pointers is useful for this problem.

Step-by-Step Explanation

Let us dry run the algorithm using a custom example.

Step 1
Use this custom example.

head = [5, 8, 3, 1], pos = 1

We will solve it using fast and slow pointers.

Step 2
Look at the first important value from the example and create the variables needed by the algorithm.

current_state = based on the first value
answer = not finished yet

Step 3
Move to the next useful value and update the state.

The algorithm compares the new value with the old state.
If the new value improves the answer, we update the answer.

Step 4
Continue this process until all useful values are processed.

After processing the example, we get:

Output: true

Why?
The tail connects back to node 8.

Important Code Logic

The most important part is updating the algorithm state after reading each useful value. This is where the answer becomes better step by step.

Think like this:

old_state = what we knew before
current_value = value we are checking now
new_state = updated result after using current_value

For our example, the final state gives:
Output: true

Example 1

Input:
head = [5, 8, 3, 1], pos = 1

Output:
Output: true

Explanation:
The tail connects back to node 8.

Example 2

Input:
head = [2, 4, 6, 8], pos = -1

Output:
false

Explanation:
The list has no cycle.

Python Code

Here is the complete Python solution for LeetCode #141.

class ListNode:
    def __init__(self, val=0):
        self.val = val
        self.next = None


class LinkedListCycleChecker:
    def has_cycle(self, head):
        slow = head
        fast = head

        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next

            if slow == fast:
                return True

        return False


first = ListNode(3)
second = ListNode(6)
third = ListNode(9)
fourth = ListNode(12)
first.next = second
second.next = third
third.next = fourth
fourth.next = second

checker = LinkedListCycleChecker()
print(checker.has_cycle(first))  # Output: True
print(checker.has_cycle(ListNode(5)))  # Output: False

Java Code

Here is the complete Java solution for LeetCode #141.

class ListNode {
    int val;
    ListNode next;

    ListNode(int val) {
        this.val = val;
    }
}

class LinkedListCycleChecker {
    public boolean hasCycle(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;

        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;

            if (slow == fast) {
                return true;
            }
        }

        return false;
    }

    public static void main(String[] args) {
        ListNode first = new ListNode(3);
        ListNode second = new ListNode(6);
        ListNode third = new ListNode(9);
        ListNode fourth = new ListNode(12);
        first.next = second;
        second.next = third;
        third.next = fourth;
        fourth.next = second;

        LinkedListCycleChecker checker = new LinkedListCycleChecker();
        System.out.println(checker.hasCycle(first)); // true
        System.out.println(checker.hasCycle(new ListNode(5))); // false
    }
}

Time and Space Complexity

Time Complexity: O(n)

The time complexity depends on how many values the algorithm needs to process and whether it uses sorting, binary search, heap, or traversal.

Space Complexity: O(n)

The extra space is used for the variables or data structures needed by the optimized approach.

Final Summary

LeetCode #141: Linked List Cycle becomes easier when we break it into small steps. First understand what the problem asks, then track the important state, dry run with an example, and finally write the code.