Problem statement

https://binarysearch.com/problems/Circular-Cyclic-Loop/

Solution

Equal to Leetcode 0457 Circular Array Loop.

Complexity

Time complexity is O(n), additional space is O(1), because we directly change our nums.

Code

class Solution:
    def solve(self, nums):
        def sign(q): return q/abs(q) if q != 0 else 0
        
        n = len(nums)
        for i in range(n):
            nums[i] = int(sign(nums[i]) * (abs(nums[i]) % n))

        for i in range(n):
            if nums[i] == 0 or nums[i] >= n: continue
            dr, start = sign(nums[i]), i
            while True:
                tmp = nums[start]
                nums[start] = n + i
                start = (start + tmp) % n
                if nums[start] == n + i: return True
                if nums[start] == 0 or nums[start] in range(n, n + i): break
                if sign(nums[start]) != dr: break
        return False