#141

Linked List Cycle

Easy
Hash TableLinked ListTwo PointersTwo PointersLinked List
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(n)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution uses the Floyd's Tortoise and Hare algorithm, where two pointers move at different speeds. If there's a cycle, they will eventually meet.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize two pointers, slow and fast, both starting at the head of the linked list.
  2. 2Step 2: Move slow pointer one step and fast pointer two steps in each iteration.
  3. 3Step 3: If slow and fast pointers meet, return true (cycle detected).
  4. 4Step 4: If fast pointer reaches the end (null), return false (no cycle).
solution.py15 lines
1# Full working Python code
2class ListNode:
3    def __init__(self, val=0, next=None):
4        self.val = val
5        self.next = next
6
7def hasCycle(head):
8    slow = head
9    fast = head
10    while fast and fast.next:
11        slow = slow.next
12        fast = fast.next.next
13        if slow == fast:
14            return True
15    return False

Complexity note: The time complexity is O(n) because we traverse the list at most twice. The space complexity is O(1) since we only use two pointers.

  • 1Using a set to track visited nodes can help identify cycles, but it uses extra space.
  • 2Floyd's algorithm is efficient as it uses constant space and is faster.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.