EasyNo. 0141

Linked List Cycle — LeetCode 141 Python Solution

Topics
Hash Table, Linked List, Two Pointers
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

PythonSolution
# 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

Time
O(n)
Space · auxiliary
O(n)where n is the number of nodes in the linked list

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

Related problems
No.ProblemDifficulty
0142Linked List Cycle IIMedium
0160Intersection of Two Linked ListsEasy
0138Copy List with Random PointerMedium
0146LRU CacheMedium
0202Happy NumberEasy
0349Intersection of Two ArraysEasy

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.

Free to download. Check it runs on your machine, then pick a plan.