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:
true
💡 Note:
There is a cycle: index 1 → index 0 → index 2 → index 0. All values in cycle have same direction (negative: -1, -2), and cycle length is 2 > 1.
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
Understanding the Visualization
1
Input
Circular array with movement instructions
2
Process
Follow paths and detect valid cycles
3
Output
Return true if valid cycle exists
Key Takeaway
🎯 Key Insight: Use Floyd's cycle detection with direction validation to find valid loops efficiently
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code