I have come up with a slightly different solution that passes all test cases and seems correct, however it times out when submitting.
def circular_array_loop(arr):
def _is_same_direction(value1, value2):
return (value1 > 0) == (value2 > 0)
def _is_infinite_loop(value):
return value % len(arr) == 0
for slow_index, slow_value in enumerate(arr):
fast_index = slow_index
fast_value = slow_value
while _is_same_direction(slow_value, fast_value) and not _is_infinite_loop(fast_value):
fast_index = (fast_index + fast_value) % len(arr)
fast_value = arr[fast_index]
if fast_index == slow_index:
return True
return False
Why is this failing?
Course: Grokking Coding Interview Patterns in Python - Learn Interactively
Lesson: Circular Array Loop - Grokking Coding Interview Patterns in Python