Linked List Cycle II — LeetCode 142 Python Solution
MediumHash TableLinked ListTwo Pointers
- Problem
- #142
- Pattern
- Linked List
- Reading time
- 3 min
- Source
- leetcode.com
The problem
Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null.
Example
- Input
- head = [3,2,0,-4], pos = 1
- Output
- tail connects to node index 1
- Explanation
- There is a cycle in the linked list, where tail connects to the second node.
Python solution
Python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
fast = slow = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
ans = head
while ans != slow:
ans = ans.next
slow = slow.next
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the number of nodes in the linked list |
| Space | O(1) auxiliary |
Pattern: Linked List
Rewire pointers in place, with a dummy head and a saved next to keep it safe. LeetCode 142. Linked List Cycle II 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
Frequently asked questions
- How hard is LeetCode 142. Linked List Cycle II?
- LeetCode 142. Linked List Cycle II is rated Medium on LeetCode.
- What is the time complexity of LeetCode 142. Linked List Cycle II?
- The Python solution on this page runs in O(n), where n is the number of nodes in the linked list.
- What is the space complexity of LeetCode 142. Linked List Cycle II?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 142. Linked List Cycle II cover?
- LeetCode 142. Linked List Cycle II is tagged Hash Table, Linked List and Two Pointers on LeetCode.