Linked List Cycle — LeetCode 141 Python Solution

EasyHash TableLinked ListTwo Pointers
Problem
#141
Reading time
3 min

The problem

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.

Example

Input
head = [3,2,0,-4], pos = 1
Output
true
Explanation
There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).

Python solution

Python
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None


class Solution:
    def hasCycle(self, head: Optional[ListNode]) -> bool:
        s = set()
        while head:
            if head in s:
                return True
            s.add(head)
            head = head.next
        return False

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n), where n is the number of nodes in the linked list auxiliary

Pattern: Linked List

Rewire pointers in place, with a dummy head and a saved next to keep it safe. LeetCode 141. Linked List Cycle is filed here because LeetCode tags it Linked List, which is the vocabulary this hub collects.

The linked list guide has the Python template for the pattern and the 75 LeetCode problems that use it.

Related problems

On study lists

This problem is on Blind 75, NeetCode 150, Grind 75 and Top Interview 150.

Frequently asked questions

How hard is LeetCode 141. Linked List Cycle?
LeetCode 141. Linked List Cycle is rated Easy on LeetCode.
What is the time complexity of LeetCode 141. Linked List Cycle?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 141. Linked List Cycle?
The Python solution on this page uses O(n), where n is the number of nodes in the linked list auxiliary space.
What topics does LeetCode 141. Linked List Cycle cover?
LeetCode 141. Linked List Cycle is tagged Hash Table, Linked List and Two Pointers on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview