Skip to content

Commit 13d869d

Browse files
141. Linked List Cycle
Difficulty: Easy 17 / 17 test cases passed. Runtime: 36 ms Memory Usage: 17.4 MB
1 parent 6e59741 commit 13d869d

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

Easy/141.LinkedListCycle.py

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
"""
2+
Given head, the head of a linked list, determine if the linked list has
3+
a cycle in it.
4+
5+
There is a cycle in a linked list if there is some node in the list that
6+
can be reached again by continuously following the next pointer.
7+
Internally, pos is used to denote the index of the node that tail's next
8+
pointer is connected to. Note that pos is not passed as a parameter.
9+
10+
Return true if there is a cycle in the linked list. Otherwise, return
11+
false.
12+
13+
Example:
14+
Input: head = [3,2,0,-4], pos = 1
15+
Output: true
16+
Explanation: There is a cycle in the linked list, where the tail connects
17+
to the 1st node (0-indexed).
18+
19+
Example:
20+
Input: head = [1,2], pos = 0
21+
Output: true
22+
Explanation: There is a cycle in the linked list, where the tail connects
23+
to the 0th node.
24+
25+
Example:
26+
Input: head = [1], pos = -1
27+
Output: false
28+
Explanation: There is no cycle in the linked list.
29+
30+
Constraints:
31+
- The number of the nodes in the list is in the range [0, 10**4].
32+
- -10**5 <= Node.val <= 10**5
33+
- pos is -1 or a valid index in the linked-list.
34+
35+
Follow up: Can you solve it using O(1) (i.e. constant) memory?
36+
"""
37+
#Difficulty: Easy
38+
#17 / 17 test cases passed.
39+
#Runtime: 36 ms
40+
#Memory Usage: 17.4 MB
41+
42+
#Runtime: 36 ms, faster than 99.38% of Python3 online submissions for Linked List Cycle.
43+
#Memory Usage: 17.4 MB, less than 99.22% of Python3 online submissions for Linked List Cycle.
44+
45+
# Definition for singly-linked list.
46+
# class ListNode:
47+
# def __init__(self, x):
48+
# self.val = x
49+
# self.next = None
50+
51+
class Solution:
52+
def hasCycle(self, head: ListNode) -> bool:
53+
s = set()
54+
while head:
55+
if head in s:
56+
return True
57+
s.add(head)
58+
head = head.next
59+
return False

0 commit comments

Comments
 (0)