Linked List Cycle — LeetCode 141 Python Solution
- Problem
- #141
- Pattern
- Linked List
- Reading time
- 3 min
- Source
- leetcode.com
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
# 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 FalseComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(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.