Given a circular array nums
of integers, determine if there is a loop in nums
. A loop must start and end at the same index, and the loop’s length is at least 2. The movement for a loop is defined in the following way:
i
to index j
is determined by j = (i + nums[i]) % n
, where n
is the length of the array.nums[i]
.Return True
if there is a loop in nums
, or False
otherwise.
nums
array?
nums
array from the problem statement. They can be positive or negative.nums
be zero?
nums
be?
10^5
elements.Let’s proceed with the solution now.
def circularArrayLoop(nums):
def next_index(i):
n = len(nums)
return (i + nums[i]) % n # ensures circular indexing
n = len(nums)
if n < 2:
return False
for i in range(n):
if nums[i] == 0:
continue
slow, fast = i, next_index(i)
# Detect loop using two pointers.
while (nums[fast] * nums[i] > 0) and (nums[next_index(fast)] * nums[i] > 0):
if slow == fast:
if slow == next_index(slow): # Check for one-element loop
break
return True
slow = next_index(slow)
fast = next_index(next_index(fast))
# If no loop found, set all elements along the path to 0 to mark them.
slow = i
sign = nums[i]
while nums[slow] * sign > 0:
next_i = next_index(slow)
nums[slow] = 0
slow = next_i
return False
This solution uses Floyd’s Cycle Detection Algorithm in an array context with boundary conditions for circular indexing and ensuring direction consistency.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?