Circular Array Loop - Problem
You are playing a game involving a circular array of non-zero integers nums. Each nums[i] denotes the number of indices forward/backward you must move if you are located at index i:
- If
nums[i]is positive, movenums[i]steps forward - If
nums[i]is negative, moveabs(nums[i])steps backward
Since the array is circular, you may assume that moving forward from the last element puts you on the first element, and moving backwards from the first element puts you on the last element.
A cycle in the array consists of a sequence of indices seq of length k where:
- Following the movement rules above results in the repeating index sequence
seq[0] -> seq[1] -> ... -> seq[k-1] -> seq[0] -> ... - Every
nums[seq[j]]is either all positive or all negative k > 1(cycle must have more than one element)
Return true if there is a cycle in nums, or false otherwise.
Input & Output
Example 1 — Valid Cycle
$
Input:
nums = [2,-1,1,-2]
›
Output:
false
💡 Note:
Starting from any index, we cannot form a valid cycle. From index 1: 1→0→2→3→1, but this cycle has mixed directions (nums[0]=2 positive, nums[1]=-1 negative), violating the same-direction rule.
Example 2 — No Valid Cycle
$
Input:
nums = [-1,2]
›
Output:
false
💡 Note:
Index 0 moves to index 1, index 1 moves to index 1 (self-loop). Self-loops are invalid since cycle length must be > 1.
Example 3 — Direction Change
$
Input:
nums = [-2,1,-1,-2,-2]
›
Output:
false
💡 Note:
No valid cycle exists because paths either lead to direction changes or form invalid cycles.
Constraints
- 1 ≤ nums.length ≤ 5000
- -1000 ≤ nums[i] ≤ 1000
- nums[i] ≠ 0
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code