Skip to content

Commit 6cab591

Browse files
committed
linked-list-cycle solution
1 parent 5b01c43 commit 6cab591

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

linked-list-cycle/devyejin.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# Definition for singly-linked list.
2+
class ListNode:
3+
def __init__(self, x):
4+
self.val = x
5+
self.next = None
6+
7+
from typing import Optional
8+
9+
# time complexity O(n)
10+
# space complexity O(1)
11+
class Solution:
12+
def hasCycle(self, head: Optional[ListNode]) -> bool:
13+
slow, fast = head, head
14+
while fast and fast.next:
15+
slow = slow.next
16+
fast = fast.next.next
17+
18+
if slow == fast:
19+
return True
20+
return False
21+
22+
23+
# time complexity O(n)
24+
# space complexity O(n)
25+
# class Solution:
26+
# def hasCycle(self, head: Optional[ListNode]) -> bool:
27+
# visited = set()
28+
# while head:
29+
# if head in visited:
30+
# return True
31+
# visited.add(head)
32+
# head = head.next
33+
# return False
34+
35+

0 commit comments

Comments
 (0)