Skip to content

Commit faed742

Browse files
committed
O(n) w/ O(1) solution
1 parent cba9300 commit faed742

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

Python/chapter02/2.8 - Loop Detection/miguel_soln_2.8.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,26 @@ def __eq__(self, other: object):
164164
return a is None and b is None
165165

166166

167+
def loop_detection_linear_time_const_space(ll: LinkedList):
168+
"""
169+
This function will determine if there is a
170+
cycle in the input linked list.
171+
A linked list is 'circular' when a node's
172+
next pointer points to an earlier node, so
173+
as to make a loop in the linked list.
174+
Runtime: O(n)
175+
Space Complexity: O(1)
176+
:param ll: an input linked list
177+
:return: the corrupt node or None
178+
"""
179+
curr_node = ll.head
180+
while curr_node is not None:
181+
if curr_node is ll.tail.next:
182+
return curr_node
183+
curr_node = curr_node.next
184+
return None
185+
186+
167187
def loop_detection_const_space(ll: LinkedList) -> Optional[Node]:
168188
"""
169189
This function will determine if there is a
@@ -258,6 +278,7 @@ def test_loop_detection(self):
258278
for ll, corrupt_node in self.loop_detection_test_cases:
259279
self.assertEqual(loop_detection(ll), corrupt_node)
260280
self.assertEqual(loop_detection_const_space(ll), corrupt_node)
281+
self.assertEqual(loop_detection_linear_time_const_space(ll), corrupt_node)
261282

262283
def test_loop_detection_single_node_ll(self):
263284
ll = LinkedList()
@@ -266,11 +287,13 @@ def test_loop_detection_single_node_ll(self):
266287
ll.head.next = corrupt_node
267288
self.assertEqual(loop_detection(ll), corrupt_node)
268289
self.assertEqual(loop_detection_const_space(ll), corrupt_node)
290+
self.assertEqual(loop_detection_linear_time_const_space(ll), corrupt_node)
269291

270292
def test_loop_detection_empty_ll(self):
271293
ll = LinkedList()
272294
self.assertIsNone(loop_detection(ll))
273295
self.assertIsNone(loop_detection_const_space(ll))
296+
self.assertIsNone(loop_detection_linear_time_const_space(ll))
274297

275298
def test_loop_detection_non_corrupt_ll(self):
276299
for ll in [
@@ -280,6 +303,7 @@ def test_loop_detection_non_corrupt_ll(self):
280303
]:
281304
self.assertIsNone(loop_detection(ll))
282305
self.assertIsNone(loop_detection_const_space(ll))
306+
self.assertIsNone(loop_detection_linear_time_const_space(ll))
283307

284308

285309
if __name__ == '__main__':

0 commit comments

Comments
 (0)