LeetCode 457 Circular Array Loop

LeetCode 457 Circular Array Loop Problem

Download Code
class Solution:
    def circularArrayLoop(self, nums: List[int]) -> bool:
        for i in range(len(nums)):
            if nums[i] == 0:
                continue
            
            # if slow and fast pointers collide, then there exists a loop
            slow = i
            fast = self.index(nums, slow)
            while nums[slow] * nums[fast] > 0 and nums[slow] * nums[self.index(nums, fast)] > 0:
                if slow == fast and fast != self.index(nums, fast):
                    return True
                elif slow == fast and fast == self.index(nums, fast):
                    break
                slow = self.index(nums, slow)
                fast = self.index(nums, self.index(nums, fast))
                
            # set path to all 0s since it doesn't work
            runner = i
            value = nums[runner]
            while nums[runner] * value > 0:
                temp = self.index(nums, runner)
                nums[runner] = 0
                runner = temp
        return False
            
    def index(self, nums, index):
        length = len(nums)
        return (index + nums[index] + length) % length
Download Circular Array Loop.py

List of all Circular Array Loop problems

Leetcode 457 Circular Array Loop problem solution in python3 with explanation. This is the best place to expand your knowledge and get prepared for your next interview.

Feedback is the most important part of any website.

If you have any query, suggestion or feedback, Please feel free to contact us.