Skip to content

Commit 54afc6a

Browse files
Chris WuChris Wu
Chris Wu
authored and
Chris Wu
committed
no message
1 parent ae52288 commit 54afc6a

File tree

1 file changed

+34
-4
lines changed

1 file changed

+34
-4
lines changed

problems/linked-list-cycle.py

Lines changed: 34 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,41 @@
1-
#https://leetcode.com/problems/linked-list-cycle/
1+
#Two Pointers
2+
#If the linked list has cycle, the fast pointer will eventually catch up.
3+
#time: O(N).
4+
#space: O(1).
25
class Solution(object):
36
def hasCycle(self, head):
47
fast = head
58
slow = head
69
while fast and fast.next:
710
fast = fast.next.next
811
slow = slow.next
9-
if (fast==slow):
10-
return True
11-
return False
12+
if fast==slow: return True
13+
return False
14+
15+
#Flag
16+
#Use a flag that stores on the nodes to know if we visited or not.
17+
#time: O(N).
18+
#space: O(N), for each node we use O(1) and there are N nodes.
19+
class Solution(object):
20+
def hasCycle(self, head):
21+
curr = head
22+
while curr:
23+
if hasattr(curr, 'visited') and curr.visited: return True
24+
curr.visited = True
25+
curr = curr.next
26+
return False
27+
28+
#HashTable
29+
#Use a hash-table to store the visited nodes
30+
#time: O(N).
31+
#space: O(N).
32+
class Solution(object):
33+
def hasCycle(self, head):
34+
visited = {}
35+
curr = head
36+
while curr:
37+
if curr in visited: return True
38+
visited[curr] = None
39+
curr = curr.next
40+
return False
41+

0 commit comments

Comments
 (0)