You are playing a game on a circular array nums of non-zero integers. Each nums[i] is the number of indices you must move forward or backward when you are at index i.
-
If
nums[i]
is positive, move
nums[i]
steps forward.
-
If
nums[i]
is negative, move
abs(nums[i])
steps backward.
Since the array is circular, moving forward from the last element puts you on the first element, and moving backward from the first element puts you on the last element.
A cycle in the array is a sequence of indices seq of length k where:
-
following the movement rules gives the repeating index sequence
seq[0] -> seq[1] -> ... -> seq[k - 1] -> seq[0] -> ...
,
-
the values
nums[seq[j]]
are either all positive or all negative, and
-
k > 1
.
Return True if there is a cycle in nums, or False otherwise.
Function Signature
def circular_array_loop(nums: list[int]) -> bool:
Rules
-
From index
i
you land on index
(i + nums[i]) mod n
, where
n = len(nums)
and the result is taken in the range
0
to
n - 1
.
-
The cycle can be anywhere in the array. It does not have to pass through index 0.
-
Only the indices on the cycle must share a sign. Indices that lead into a cycle without being on it are ignored.
-
An index that moves back onto itself (its value is a multiple of
n
) forms a cycle of length 1, which does not count.
Constraints
-
1 <= len(nums) <= 5000
-
-1000 <= nums[i] <= 1000
-
nums[i] != 0
Examples
Input: nums = [2,-1,1,2,2]
Output: True
Index 0 moves to 2, index 2 moves to 3, and index 3 moves back to 0. That cycle has length 3 and its values 2, 1, 2 are all positive.
Input: nums = [-1,-2,-3,-4,-5]
Output: False
Every index moves to index 4, and index 4 moves to itself. The only cycle has length 1, so it does not count.
Input: nums = [1,-1]
Output: False
Index 0 moves to 1 and index 1 moves back to 0, so the two indices form a cycle of length 2. It mixes a positive and a negative value, so it is not valid.