Skip to content

Commit 77aa070

Browse files
committed
linked-list-cycle sol (py)
1 parent bb5593f commit 77aa070

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

linked-list-cycle/hi-rachel.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# Definition for singly-linked list.
2+
# class ListNode:
3+
# def __init__(self, x):
4+
# self.val = x
5+
# self.next = None
6+
7+
"""
8+
TC: O(n)
9+
SC: O(n)
10+
"""
11+
class Solution:
12+
def hasCycle(self, head: Optional[ListNode]) -> bool:
13+
visited = set()
14+
while head:
15+
# 해당 노드 이미 방문한 적 있으면
16+
if head in visited:
17+
return True
18+
# 방문한 적 없으면 set에 넣기
19+
visited.add(head)
20+
# 다음 노드로 이동
21+
head = head.next
22+
23+
# cycle이 없음
24+
return False
25+
26+
"""
27+
The tortoise and hare
28+
29+
TC: O(n)
30+
SC: O(1)
31+
"""
32+
class Solution:
33+
def hasCycle(self, head: Optional[ListNode]) -> bool:
34+
slow, fast = head, head
35+
while fast and fast.next:
36+
slow = slow.next
37+
fast = fast.next.next
38+
if slow == fast:
39+
return True
40+
return False

0 commit comments

Comments
 (0)