@@ -164,6 +164,26 @@ def __eq__(self, other: object):
164
164
return a is None and b is None
165
165
166
166
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
+
167
187
def loop_detection_const_space (ll : LinkedList ) -> Optional [Node ]:
168
188
"""
169
189
This function will determine if there is a
@@ -258,6 +278,7 @@ def test_loop_detection(self):
258
278
for ll , corrupt_node in self .loop_detection_test_cases :
259
279
self .assertEqual (loop_detection (ll ), corrupt_node )
260
280
self .assertEqual (loop_detection_const_space (ll ), corrupt_node )
281
+ self .assertEqual (loop_detection_linear_time_const_space (ll ), corrupt_node )
261
282
262
283
def test_loop_detection_single_node_ll (self ):
263
284
ll = LinkedList ()
@@ -266,11 +287,13 @@ def test_loop_detection_single_node_ll(self):
266
287
ll .head .next = corrupt_node
267
288
self .assertEqual (loop_detection (ll ), corrupt_node )
268
289
self .assertEqual (loop_detection_const_space (ll ), corrupt_node )
290
+ self .assertEqual (loop_detection_linear_time_const_space (ll ), corrupt_node )
269
291
270
292
def test_loop_detection_empty_ll (self ):
271
293
ll = LinkedList ()
272
294
self .assertIsNone (loop_detection (ll ))
273
295
self .assertIsNone (loop_detection_const_space (ll ))
296
+ self .assertIsNone (loop_detection_linear_time_const_space (ll ))
274
297
275
298
def test_loop_detection_non_corrupt_ll (self ):
276
299
for ll in [
@@ -280,6 +303,7 @@ def test_loop_detection_non_corrupt_ll(self):
280
303
]:
281
304
self .assertIsNone (loop_detection (ll ))
282
305
self .assertIsNone (loop_detection_const_space (ll ))
306
+ self .assertIsNone (loop_detection_linear_time_const_space (ll ))
283
307
284
308
285
309
if __name__ == '__main__' :
0 commit comments