LeetCode 141: Linked List Cycle Solution

Master LeetCode problem 141 (Linked List Cycle), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

141. Linked List Cycle

Problem Explanation

Explanation

To determine if a linked list has a cycle, we can use the "fast and slow pointers" approach. We initialize two pointers, slow and fast, both pointing to the head of the linked list. The slow pointer moves one step at a time while the fast pointer moves two steps at a time. If there is a cycle in the linked list, the fast pointer will eventually meet the slow pointer. If there is no cycle, the fast pointer will reach the end of the list (null) before the slow pointer.

Time Complexity

The time complexity of this approach is O(n), where n is the number of nodes in the linked list.

Space Complexity

The space complexity of this approach is O(1) as we are using only two extra pointers.

Solution Code

public class Solution {
    public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }
        
        ListNode slow = head;
        ListNode fast = head.next;
        
        while (slow != fast) {
            if (fast == null || fast.next == null) {
                return false;
            }
            slow = slow.next;
            fast = fast.next.next;
        }
        
        return true;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 141 (Linked List Cycle)?

This page provides optimized solutions for LeetCode problem 141 (Linked List Cycle) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 141 (Linked List Cycle)?

The time complexity for LeetCode 141 (Linked List Cycle) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 141 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 141 in Java, C++, or Python.

Back to LeetCode Solutions